Grant Lambda function access to API and Data
Function access to defineData
can be configured using an authorization rule on the schema object.
import { a, defineData, type ClientSchema} from '@aws-amplify/backend';import { functionWithDataAccess } from '../function/data-access/resource';
const schema = a .schema({ Todo: a.model({ name: a.string(), description: a.string(), isDone: a.boolean() }) }) .authorization(allow => [allow.resource(functionWithDataAccess)]);
export type Schema = ClientSchema<typeof schema>;
export const data = defineData({ schema});
Create a new directory and a resource file, amplify/functions/data-access/resource.ts
. Then, define the Function with defineFunction
:
import { defineFunction } from '@aws-amplify/backend';
export const functionWithDataAccess = defineFunction({ name: 'data-access',});
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.
const schema = a .schema({ Todo: a.model({ name: a.string(), description: a.string(), isDone: a.boolean() }) }) .authorization(allow => [ allow.resource(functionWithDataAccess).to(['query', 'listen']) ]); // allow query and subscription operations but not mutations
Access the API using aws-amplify
In the handler file for your function, configure the Amplify data client
import type { Handler } from 'aws-lambda';import type { Schema } from '../../data/resource';import { Amplify } from 'aws-amplify';import { generateClient } from 'aws-amplify/data';import { getAmplifyDataClientConfig } from '@aws-amplify/backend/function/runtime';import { env } from '$amplify/env/<function-name>'; // replace with your function name
const { resourceConfig, libraryOptions } = await getAmplifyDataClientConfig(env);
Amplify.configure(resourceConfig, libraryOptions);
const client = generateClient<Schema>();
export const handler = async (event) => { // your function code goes here}
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.
const client = generateClient<Schema>();
export const handler: Handler = async (event) => { const { errors: createErrors, data: newTodo } = await client.models.Todo.create({ name: "My new todo", description: "Todo description", isDone: false, })
const { errors: listErrors, data: todos } = await client.models.Todo.list();
return event;};