LoginSignup
0
0

More than 1 year has passed since last update.

AmplifyでGraphQLを使いつつ、Lambdaを非認証ユーザーで叩く(Typescript)

Last updated at Posted at 2022-01-09

概要

AWS Amplifyにて非認証ユーザーで外部のAPIを叩いて、JSONを引っ張ってくるところを作りたかったが、色々詰まったのでシェア

環境

  • "aws-amplify": "^4.3.12",
  • "typescript": "~4.1.5"
  • "vue": "^3.0.0"

Amplifyの各環境を作る

cmd
amplify configure
amplify init
amplify add api
amplify add function

このあたりはこの辺を見れば詰まらないと思う。
ファンクション名はreadListとした。

Authを設定する

ここからがポイント。
まず、認証の方法だが、非認証ユーザーでのアクセスを許可する場合は、API KeyとIAMがあるが、
API Keyは日付制限(最長365日)があるので、IAMとする。

cmd
amplify add auth

すると、問が出てるくので以下を選択する。

cmd
Do you want to use the default authentication and security configuration? (Use arrow keys):
 Manual configuration

進めると、更に問が出てくるので以下と答える。

cmd
Select the authentication/authorization services that you want to use: (Use arrow keys)
 User Sign-Up, Sign-In, connected with AWS IAM controls (Enables per-user Storage features for images or other content, Analytics, and more)

さらに進めると、更に問が出てくるので以下と答える。

cmd
? Allow unauthenticated logins? (Provides scoped down permissions that you can control via AWS IAM)
 Yes

これで、認証の設定は完了。

GraphQLのスキーマを編集

次にGraphQLのスキーマを変更していく。
以下の設定とした。

schema.graphql
input AMPLIFY { globalAuthRule: AuthRule = { allow: public } } # FOR TESTING ONLY!

type Query {
  readList: String
  @function(name: "readList-${env}")
  @auth(rules: [
    {allow: public, provider: iam},
  ])
}

ファンクションの編集

ファンクションの編集をする。
今回はファンクション名はreadListとして、コードは以下とした。

index.js
exports.handler = async () => {
  return JSON.stringify('Hello from Lambda!');
};

ここで一旦、プッシュしておく。

cmd
 amplify push

フロントの編集

今回はVueのサンプルページをそのまま使用した。

Home.vue
<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png" />
    <HelloWorld msg="Welcome to Your Vue.js + TypeScript App" />
  </div>
</template>

<script lang="ts">
import { Options, Vue } from 'vue-class-component';
import HelloWorld from '@/components/HelloWorld.vue';
import Amplify, { API, graphqlOperation } from 'aws-amplify';
import config from '@/aws-exports';
import { readList } from '@/graphql/queries';

@Options({
  components: {
    HelloWorld,
  },
})
export default class Home extends Vue {
  public async mounted(): Promise<void> {
    Amplify.configure(config);
    const res = await API.graphql(graphqlOperation(readList));
    console.log(res);
  }
}
</script>

しかし、このままだとエラーが出るため以下の対応をする。
ファイル名 aws-exports.js → aws-exports.ts に変更する。
こちらの記事を参考にさせてもらった。ありがとうございます。)

また、aws-exports.tsに以下の記載があるか確認して、ない場合は追加する。
"aws_appsync_authenticationType": "AWS_IAM"

確認

結果を確認する。
Homeページにアクセスして、コンソールを開いて確認すると
readList: "\"Hello from Lambda!\" と表示されていると思う。

0
0
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
0
0