💡

LambdaからGen2 Client経由で呼べるようになって便利になった話

に公開

🤯 Amplfiy Gen2を利用したLambdaの中で、backend/dataにアクセスしたいが大変問題

Gen2 Userなら必ずぶつかる壁の1つでもあるんじゃないかなと思ってる問題で、defineFunctionで定義した、lambdaからconst schema = a.schemaのデータに対してデータ取得したい場合などがあった場合、swift clientでよくやる、コードを生成して、aws-appsyncを利用して、AppSync Clientを叩いて実装ということが必要でした。
これらを利用したユースケースとして、マルチテナントで運用してるSaasで利用したい場合に、comapnyIduserIDなどでa.schemaで、作成したTableに、データは存在してるか?的なユースケースの時に、利用することが多くあります。

https://speakerdeck.com/magisystem0408/amplify-x-iotlian-xi-dian-qi-zi-dong-che-ev-tiyazingusutesiyonsisutemunoshao-jie?slide=6

npx ampx generate graphql-client-code --format graphql-codegen --statement-target typescript --out amplify/generated/types

https://docs.amplify.aws/swift/build-a-backend/data/set-up-data/

他にもこのようなやり方もありました。
https://dev.classmethod.jp/articles/amplify-gen2-appsync-mutation-lambda/

ですが、下記の問題が発生しがちでした。

defineFunctionで定義したlambdaの中の一部
const appSyncClient = new AWSAppSyncClient({ 
            url: process.env.AWS_APPSYNC_ENDPOINT,
            region: process.env.AWS_REGION,
            auth:{
                type: "AWS_IAM",
                credentials: {
                    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
                    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
                    sessionToken: process.env.AWS_SESSION_TOKEN,
                }
            },
            disableOffline: true,
        });
<!--PAIN: 自分で型(ex. CreateCompanyUserMutation, CreateCompanyUserMutationVariables)保管をしないといけない  -->
await appSyncClient.mutate<CreateCompanyUserMutation, CreateCompanyUserMutationVariables>({
    mutation: gql`${mutations.createCompanyUser}`,
    variables: {
        input: {
            email: email,
            companyId: companyId,
            role: "User",
            status: ComapnyUserStatus.INVITE
        }
    }
});

## 🥺 lambdaの中でもgenerateClientを利用したい。
できれば下記を利用して、呼び出したい。

import { generateClient } from 'aws-amplify/data';
import { type Schema } from '../amplify/data/resource'

const client = generateClient<Schema>();

const { errors, data: newTodo } = await client.models.Todo.create({
  content: "My new todo",
  isDone: true,
})

https://docs.amplify.aws/react/build-a-backend/data/mutate-data/

✅ Lambdaの中でもgenerateClientをSupport

getAmplifyDataClientの改善によって、参照ができるようになったみたい

https://github.com/aws-amplify/amplify-backend/pull/2409

https://github.com/aws-amplify/amplify-backend/commits/main/packages/backend-function/src/runtime/get_amplify_clients_configuration.ts

どうやら、ResourceConfigにAppSyncのEndpointの情報を持ってることがわかった。

export type ResourceConfig = {
  API: {
    GraphQL: {
      endpoint: string;
      region: string;
      defaultAuthMode: 'iam';
      // Using `any` to avoid reproducing 100+ lines of typing to match the expected shape defined in aws-amplify:
      // https://github.com/aws-amplify/amplify-js/blob/main/packages/core/src/singleton/API/types.ts#L143-L153
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      modelIntrospection: any;
    };
  };
};
/* eslint-enable @typescript-eslint/naming-convention */

https://github.com/aws-amplify/amplify-backend/blob/3b4f18fab5c0bfdebab06b598246420e8f3d1b52/packages/backend-function/src/runtime/get_amplify_clients_configuration.ts#L32C19-L45

Discord Channelにてhelpも上がっていた

ちなみに、下記でも紹介している。

https://qiita.com/tttol777/items/54931834b4c404ea1913

以前まではできなかったらしいが、対応したらしい。😀😀
https://docs.amplify.aws/react/build-a-backend/data/customize-authz/grant-lambda-function-access-to-api/

import { env } from "$amplify/env/<Your defineFunction Name>"
import { getAmplifyDataClientConfig } from "@aws-amplify/backend/function/runtime"
import { Amplify } from "aws-amplify"
import { generateClient } from "aws-amplify/api"

const { resourceConfig, libraryOptions } = await getAmplifyDataClientConfig(env)

Amplify.configure(
    resourceConfig, libraryOptions)

const client = generateClient<Schema>()

export const handler =()=>{...}

どうやら、lambdaの中で、Amplify.configureをして、clientを作るらしい。

リクエストするコードが必要なくなったため、コード量が減ってわかりやすくなった。

## 忘備録 commutity Builderのswagが1ヶ月前ぐらいに届いた

Discussion