LoginSignup
3
1

More than 3 years have passed since last update.

Amplifyをシンプルなライブラリとして使うサンプル

Last updated at Posted at 2021-02-08

対象

Amplifyを使ってAWSのサービスを簡単に叩きたい人

準備

任意のディレクトリで

npm init

からの

npm i aws-amplify

としておきます。

Amplifyライブラリの仕組み

amplify addやらでサービスを構築していくと、amplifyのconfigが自動的に構成されて、気が付かないうちに便利なツールになっているのが特徴です。
逆に言えばこれらを自分で書いてちょっとした便利ツールとして使うことも可能です。
Cogmnitoの認証やAPIの呼び出しなど、Amplifyライブラリを使用したほうが断然楽です。

例えばサインインでは


const Amplify = require('aws-amplify')

const config {
  "aws_project_region":"ap-northeast-1",
  "aws_cognito_identity_pool_id":"ap-northeast-1:0000000....",
  "aws_cognito_region":"ap-northeast-1",
  "aws_user_pools_id":"ap-northeast-1_xxxxx",
  "aws_user_pools_web_client":"xxxxx"
}

Amplify.default.configure(config)

const userId = "hoge"
const password = "pass"

Amplify.Auth.signIn(userId,password).then(user => {
  // 成功時


}).catch(err => {
  // 失敗時
})

サインインを行うとCognitoUserオブジェクトが返ってきます。
AWS Amplify API#signIn

CognitoUserの中身はJSON.stringfyでもしてダンプすれば見れます。
大体は


Amplify.Auth.signIn(userId,password).then(user => {
  // 成功時
  user.signInUserSession.idToken
}).catch(err => {
  // 失敗時
})

などして使いたいトークンを取得するのかと思います。

で、サインイン後は、任意のタイミングでログイン情報を取得することが可能です。
トークンなども取得できるので、便利です。

Amplify.Auth.currentAuthenticatedUser()

ここで取得できるのもまたCognitoUserオブジェクトです。
たしかトークン期限が切れている場合でも、このメソッドを呼ぶと更新トークンを使用して新らしいトークンが取得出来るはずです。

トークン期限切れの場合は、エラーで返してくれると嬉しいんですけどね。

APIも同じようにconfigに追加して初期化すればいつでも簡単に呼び出しできます。

Amplify add apiとしてREST APIを一度生成してみれば、どういう設定をAmplifyに食わしているかがわかります。
あとはAPI名とメソッドだけ指定すればサクッと呼べるので便利ですね。

const apiname = "hogeApi"
const path = "/test"
const params = {
  headers:{
    hoge:"foo"
  }
  body: {
    id:"aaaa"
  }
}
await Amplify.API.post(apiname,path,params).then(response => {
  // 成功時
}).catch(err => {
  // エラー時
})
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1