a year ago

Vue2 + TypeScript + Nuxt.js + amplify初期セットアップ


nuxtプロジェクト作成

% npx create-nuxt-app nuxt-amplify
Need to install the following packages:
  create-nuxt-app
Ok to proceed? (y) y
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated

create-nuxt-app v3.7.1
✨  Generating Nuxt.js project in nuxt-amplify
? Project name: nuxt-amplify
? Programming language: TypeScript
? Package manager: Npm
? UI framework: Bootstrap Vue
? Nuxt.js modules: Axios - Promise based HTTP client, Progressive Web App (PW
A)
? Linting tools: ESLint
? Testing framework: Jest
? Rendering mode: Single Page App
? Deployment target: Static (Static/Jamstack hosting)
? Development tools: (Press <space> to select, <a> to toggle all, <i> to inve
rt selection)
? Continuous integration: None
? Version control system: Git

amplify backend作成

% amplify init
? Initialize the project with the above configuration? No
? Enter a name for the environment dev
? Choose your default editor: IntelliJ IDEA
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using vue
? Source Directory Path:  .
? Distribution Directory Path: dist
? Build Command:  npm run generate
? Start Command: npm run start
Using default provider  awscloudformation
? Select the authentication method you want to use: AWS profile

For more information on AWS Profiles, see:
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html

? Please choose the profile you want to use amplify01

frontライブラリインストール

% npm install aws-amplify @aws-amplify/ui-vue
  • ~/plugins/amplify.ts

    import Vue from 'vue'
    import Amplify from 'aws-amplify'
    import '@aws-amplify/ui-vue'
    import awsExports from '../aws-exports'
    
    Amplify.configure(awsExports)
    Vue.use(Amplify)
    
  • ~/utils/shims.d.ts`

    declare module 'aws-amplify'
    

Graph QL API作成

% amplify add api
? Please select from one of the below mentioned services: GraphQL
? Provide API name: nuxtamplify
? Choose the default authorization type for the API API key
? Enter a description for the API key: nuxt-amplify
? After how many days from now the API key should expire (1-365): (7) 
mito.shimada@AMAC02Z8052LVDT nuxt-amplify % 
mito.shimada@AMAC02Z8052LVDT nuxt-amplify % amplify add api
? Please select from one of the below mentioned services: GraphQL
? Provide API name: nuxtamplify
? Choose the default authorization type for the API Amazon Cognito User Pool
Using service: Cognito, provided by: awscloudformation
 
 The current configured provider is Amazon Cognito. 
 
 Do you want to use the default authentication and security configuration? Default configuration
 Warning: you will not be able to edit these selections. 
 How do you want users to be able to sign in? Email, Username
 Do you want to configure advanced settings? No, I am done.
Successfully added auth resource nuxtamplify13f89588 locally

Some next steps:
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

? Do you want to configure advanced settings for the GraphQL API No, I am done.
? Do you have an annotated GraphQL schema? No
? Choose a schema template: One-to-many relationship (e.g., “Blogs” with “Posts” and “Comments”)

The following types do not have '@auth' enabled. Consider using @auth with @model
         - Blog
         - Post
         - Comment
Learn more about @auth here: https://docs.amplify.aws/cli/graphql-transformer/auth



GraphQL schema compiled successfully.

GraphQL APIをpush

% amplify push

schema.graphqlの型

  • String(文字列型)
  • Int(整数型)
  • Float(浮動小数点型)
  • Boolean(論理型)
  • ID(ID型)

IntとFloatはJSONではnumberで表現されます。StringとIDはJSONではstringで表現されます。Booleanはそのままです。また、ID型の実態は文字列(String)ですが、GraphQLの仕様上ユニークでなければならない点でString型と区別されています。

引用 https://qiita.com/NagaokaKenichi/items/d341dc092012e05d6606

全部やり直したい時

amplify delete

認証しないとできないこと、誰でも出来ることを使い分ける

ログインしたユーザーは自由にCRUDできるが、ログインしていないユーザはreadだけにしたいケース、あると思います。

その場合、ログインしていないユーザーはIAMのUnauth roleでgraphQLを叩くように設定する必要があります。

schema.graphqlを編集

readは誰でもできるが、create, delete, updateはownerでなければできないという設定になっています。

type Post @model
@auth(rules: [
  { allow: owner, operations: [create, delete, update] },
  { allow: public, provider: iam, operations: [read] } # unauthenticated users can read
])
{
  id: ID!
  body: String!
  owner: String
}

amplify update api

% amplify update api

? Please select from one of the below mentioned services: GraphQL
? Select from the options below Walkthrough all configurations
? Choose the default authorization type for the API Amazon Cognito User Pool
Use a Cognito user pool configured as a part of this project.
? Do you want to configure advanced settings for the GraphQL API Yes, I want to make some additional changes.
? Configure additional auth types? Yes
? Choose the additional authorization types you want to configure for the API IAM
? Enable conflict detection? No

GraphQL schema compiled successfully.

amplify update auth

Allow unauthenticated logins? に対しYesで答えるのが重要

 % amplify update auth
 What do you want to do? Walkthrough all the auth configurations
 Select the authentication/authorization services that you want to use: User Sign-Up, Sign-In, connected with AWS IAM controls (Enables per-user Storage features for images or other
 content, Analytics, and more)
 Allow unauthenticated logins? (Provides scoped down permissions that you can control via AWS IAM) Yes
 Do you want to enable 3rd party authentication providers in your identity pool? No
 Do you want to add User Pool Groups? Yes
? Provide a name for your user pool group: Admin
? Do you want to add another User Pool Group Yes
? Provide a name for your user pool group: User
? Do you want to add another User Pool Group No
✔ Sort the user pool groups in order of preference · Admin, User
 Do you want to add an admin queries API? No
 Multifactor authentication (MFA) user login options: OFF
 Email based user registration/forgot password: Enabled (Requires per-user email entry at registration)
 Please specify an email verification subject: Your verification code
 Please specify an email verification message: Your verification code is {####}
 Do you want to override the default password policy for this User Pool? No
 Specify the app's refresh token expiration period (in days): 30
 Do you want to specify the user attributes this app can read and write? No
 Do you want to enable any of the following capabilities? 
 Do you want to use an OAuth flow? No
? Do you want to configure Lambda Triggers for Cognito? No

ここまでやったらpushします

amplify push

Amplify Authenticatorの日本語化

言語ライブラリをインストール

npm install @aws-amplify-jp/vocabulary-ja

nuxtならpluginの中で以下のように設定

import Vue from 'vue'
import Amplify from 'aws-amplify'
import { Translations } from '@aws-amplify/ui-components'
import '@aws-amplify/ui-vue'
import ja from '@aws-amplify-jp/vocabulary-ja'
import awsExports from '../aws-exports'

Amplify.configure({
  ...awsExports,
  aws_appsync_authenticationType: 'AWS_IAM'
})

Amplify.I18n.putVocabulariesForLanguage('ja-JP', ja(Translations))
Amplify.I18n.setLanguage('ja-JP')

Vue.use(Amplify)

ログイン、ログアウトなどのイベントフック

Hubのlistenerで認証の色々なタイミングで処理ができる。

import { Auth, Hub } from 'aws-amplify'

export default class Default extends Vue {
    mounted () {
    Hub.listen('auth', this.listener)
  }

  async listener (data: HubCapsule) {
    switch (data.payload.event) {
      case 'signIn':
        break
      case 'signUp':
        break
      case 'signOut':
        break
      case 'signIn_failure':
        break
      case 'tokenRefresh':
        break
      case 'tokenRefresh_failure':
        break
      case 'configured':
    }
  }
}

参考

https://docs.amplify.aws/lib/auth/auth-events/q/platform/js/


Related Articles