Grant Lambda function access to API and Data
Function access to defineData
can be configured using an authorization rule on the schema object.
1import {2 a,3 defineData,4 defineFunction,5 type ClientSchema6} from '@aws-amplify/backend';7
8const functionWithDataAccess = defineFunction({9 entry: '../functions/data-access.ts'10});11
12const schema = a13 .schema({14 Todo: a.model({15 name: a.string(),16 description: a.string()17 })18 })20
21export type Schema = ClientSchema<typeof schema>;22
23export const data = defineData({24 schema25});
The object returned from defineFunction
can be passed directly to allow.resource()
in the schema authorization rules. This will grant the function the ability to execute Query, Mutation, and Subscription operations against the GraphQL API. Use the .to()
method to narrow down access to one or more operations.
1const schema = a2 .schema({3 Todo: a.model({4 name: a.string(),5 description: a.string()6 })7 })
When configuring function access, the function will be provided the API endpoint as an environment variable named <defineDataName>_GRAPHQL_ENDPOINT
. The default name is amplifyData_GRAPHQL_ENDPOINT
unless you have specified a different name in defineData
.
Access the API using aws-amplify
In the handler file for your function, configure the Amplify data client
1import { Amplify } from 'aws-amplify';2import { generateClient } from 'aws-amplify/data';3import { Schema } from '../data/resource';4import { env } from '$amplify/env/<function-name>'; // replace with your function name5
6
7Amplify.configure(8 {9 API: {10 GraphQL: {11 endpoint: env.<amplifyData>_GRAPHQL_ENDPOINT, // replace with your defineData name12 region: env.AWS_REGION,13 defaultAuthMode: 'identityPool'14 }15 }16 },17 {18 Auth: {19 credentialsProvider: {20 getCredentialsAndIdentityId: async () => ({21 credentials: {22 accessKeyId: env.AWS_ACCESS_KEY_ID,23 secretAccessKey: env.AWS_SECRET_ACCESS_KEY,24 sessionToken: env.AWS_SESSION_TOKEN,25 },26 }),27 clearCredentialsAndIdentityId: () => {28 /* noop */29 },30 },31 },32 }33);34
35const dataClient = generateClient<Schema>();36
37export const handler = async (event) => {38 // your function code goes here39}
Use the command below to generate GraphQL client code to call your data backend.
npx ampx generate graphql-client-code --out <path-function-handler-dir>/graphql
Once you have generated the client code, update the function to access the data. The following code creates a todo and then lists all todos.
1const client = generateClient<Schema>();2
3export const handler = async (event) => {4 await client.graphql({5 query: createTodo,6 variables: {7 input: {8 name: "My first todo",9 description: "This is my first todo",10 },11 },12 });13
14
15 await client.graphql({16 query: listTodos,17 });18
19 return event;20};