Configure Lambda resolvers

You are currently viewing the legacy GraphQL Transformer documentation. View latest documentation

@function

The @function directive allows you to quickly & easily configure AWS Lambda resolvers within your AWS AppSync API.

Definition

1directive @function(name: String!, region: String) on FIELD_DEFINITION

Usage

The @function directive allows you to quickly connect lambda resolvers to an AppSync API. You may deploy the AWS Lambda functions via the Amplify CLI, AWS Lambda console, or any other tool. To connect an AWS Lambda resolver, add the @function directive to a field in your schema.graphql.

Let's assume you have deployed an echo function with the following contents:

1exports.handler = async function (event, context) {
2 return event.arguments.msg;
3};

If you deployed your function using the function category

The Amplify CLI provides support for maintaining multiple environments out of the box. When you deploy a function via amplify add function, it will automatically add the environment suffix to your Lambda function name. For example if you create a function named echofunction using amplify add function in the dev environment, the deployed function will be named echofunction-dev. The @function directive allows you to use ${env} to reference the current Amplify CLI environment.

1type Query {
2 echo(msg: String): String @function(name: "echofunction-${env}")
3}

If you deployed your function without amplify

If you deployed your API without amplify then you must provide the full Lambda function name. If you deployed the same function with the name echofunction then you would have:

1type Query {
2 echo(msg: String): String @function(name: "echofunction")
3}

Example: Return custom data and run custom logic

You can use the @function directive to write custom business logic in an AWS Lambda function. To get started, use amplify add function, the AWS Lambda console, or other tool to deploy an AWS Lambda function with the following contents.

For example purposes assume the function is named GraphQLResolverFunction:

1const POSTS = [
2 { id: 1, title: 'AWS Lambda: How To Guide.' },
3 { id: 2, title: 'AWS Amplify Launches @function and @key directives.' },
4 { id: 3, title: 'Serverless 101' }
5];
6const COMMENTS = [
7 { postId: 1, content: 'Great guide!' },
8 { postId: 1, content: 'Thanks for sharing!' },
9 { postId: 2, content: "Can't wait to try them out!" }
10];
11
12// Get all posts. Write your own logic that reads from any data source.
13function getPosts() {
14 return POSTS;
15}
16
17// Get the comments for a single post.
18function getCommentsForPost(postId) {
19 return COMMENTS.filter((comment) => comment.postId === postId);
20}
21
22/**
23 * Using this as the entry point, you can use a single function to handle many resolvers.
24 */
25const resolvers = {
26 Query: {
27 posts: (ctx) => {
28 return getPosts();
29 }
30 },
31 Post: {
32 comments: (ctx) => {
33 return getCommentsForPost(ctx.source.id);
34 }
35 }
36};
37
38// event
39// {
40// "typeName": "Query", /* Filled dynamically based on @function usage location */
41// "fieldName": "me", /* Filled dynamically based on @function usage location */
42// "arguments": { /* GraphQL field arguments via $ctx.arguments */ },
43// "identity": { /* AppSync identity object via $ctx.identity */ },
44// "source": { /* The object returned by the parent resolver. E.G. if resolving field 'Post.comments', the source is the Post object. */ },
45// "request": { /* AppSync request object. Contains things like headers. */ },
46// "prev": { /* If using the built-in pipeline resolver support, this contains the object returned by the previous function. */ },
47// }
48exports.handler = async (event) => {
49 const typeHandler = resolvers[event.typeName];
50 if (typeHandler) {
51 const resolver = typeHandler[event.fieldName];
52 if (resolver) {
53 return await resolver(event);
54 }
55 }
56 throw new Error('Resolver not found.');
57};

Example: Get the logged in user from Amazon Cognito User Pools

When building applications, it is often useful to fetch information for the current user. You can use the @function directive to quickly add a resolver that uses AppSync identity information to fetch a user from Amazon Cognito User Pools. First make sure you have added Amazon Cognito User Pools enabled via amplify add auth and a GraphQL API via amplify add api to an amplify project. Once you have created the user pool, get the UserPoolId from amplify-meta.json in the backend/ directory of your amplify project. You will provide this value as an environment variable in a moment. Next, using the Amplify function category, AWS console, or some other tool, deploy an AWS Lambda function with the following contents.

For example purposes assume the function is named GraphQLResolverFunction:

1/* Amplify Params - DO NOT EDIT
2You can access the following resource attributes as environment variables from your Lambda function
3var environment = process.env.ENV
4var region = process.env.REGION
5var authMyResourceNameUserPoolId = process.env.AUTH_MYRESOURCENAME_USERPOOLID
6
7Amplify Params - DO NOT EDIT */
8
9const { CognitoIdentityServiceProvider } = require('aws-sdk');
10const cognitoIdentityServiceProvider = new CognitoIdentityServiceProvider();
11
12/**
13 * Get user pool information from environment variables.
14 */
15const COGNITO_USERPOOL_ID = process.env.AUTH_MYRESOURCENAME_USERPOOLID;
16if (!COGNITO_USERPOOL_ID) {
17 throw new Error(
18 `Function requires environment variable: 'COGNITO_USERPOOL_ID'`
19 );
20}
21const COGNITO_USERNAME_CLAIM_KEY = 'cognito:username';
22
23/**
24 * Using this as the entry point, you can use a single function to handle many resolvers.
25 */
26const resolvers = {
27 Query: {
28 echo: (ctx) => {
29 return ctx.arguments.msg;
30 },
31 me: async (ctx) => {
32 var params = {
33 UserPoolId: COGNITO_USERPOOL_ID /* required */,
34 Username: ctx.identity.claims[COGNITO_USERNAME_CLAIM_KEY] /* required */
35 };
36 try {
37 // Read more: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityServiceProvider.html#adminGetUser-property
38 return await cognitoIdentityServiceProvider
39 .adminGetUser(params)
40 .promise();
41 } catch (e) {
42 throw new Error(`NOT FOUND`);
43 }
44 }
45 }
46};
47
48// event
49// {
50// "typeName": "Query", /* Filled dynamically based on @function usage location */
51// "fieldName": "me", /* Filled dynamically based on @function usage location */
52// "arguments": { /* GraphQL field arguments via $ctx.arguments */ },
53// "identity": { /* AppSync identity object via $ctx.identity */ },
54// "source": { /* The object returned by the parent resolver. E.G. if resolving field 'Post.comments', the source is the Post object. */ },
55// "request": { /* AppSync request object. Contains things like headers. */ },
56// "prev": { /* If using the built-in pipeline resolver support, this contains the object returned by the previous function. */ },
57// }
58exports.handler = async (event) => {
59 const typeHandler = resolvers[event.typeName];
60 if (typeHandler) {
61 const resolver = typeHandler[event.fieldName];
62 if (resolver) {
63 return await resolver(event);
64 }
65 }
66 throw new Error('Resolver not found.');
67};

You can connect this function to your AppSync API deployed via Amplify using this schema:

1type Query {
2 posts: [Post] @function(name: "GraphQLResolverFunction")
3}
4type Post {
5 id: ID!
6 title: String!
7 comments: [Comment] @function(name: "GraphQLResolverFunction")
8}
9type Comment {
10 postId: ID!
11 content: String
12}

This simple lambda function shows how you can write your own custom logic using a language of your choosing. Try enhancing the example with your own data and logic.

When deploying the function, make sure your function has access to the auth resource. You can run the amplify update function command for the CLI to automatically supply an environment variable named AUTH_<RESOURCE_NAME>_USERPOOLID to the function and associate corresponding CRUD policies to the execution role of the function.

After deploying your function, you can connect it to AppSync by defining some types and using the @function directive. Add this to your schema, to connect the Query.echo and Query.me resolvers to your new function.

1type Query {
2 me: User @function(name: "ResolverFunction")
3 echo(msg: String): String @function(name: "ResolverFunction")
4}
5# These types derived from https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityServiceProvider.html#adminGetUser-property
6type User {
7 Username: String!
8 UserAttributes: [Value]
9 UserCreateDate: String
10 UserLastModifiedDate: String
11 Enabled: Boolean
12 UserStatus: UserStatus
13 MFAOptions: [MFAOption]
14 PreferredMfaSetting: String
15 UserMFASettingList: String
16}
17type Value {
18 Name: String!
19 Value: String
20}
21type MFAOption {
22 DeliveryMedium: String
23 AttributeName: String
24}
25enum UserStatus {
26 UNCONFIRMED
27 CONFIRMED
28 ARCHIVED
29 COMPROMISED
30 UNKNOWN
31 RESET_REQUIRED
32 FORCE_CHANGE_PASSWORD
33}

Next run amplify push and wait as your project finishes deploying. To test that everything is working as expected run amplify api console to open the GraphiQL editor for your API. You are going to need to open the Amazon Cognito User Pools console to create a user if you do not yet have any. Once you have created a user go back to the AppSync console's query page and click "Login with User Pools". You can find the ClientId in amplify-meta.json under the key AppClientIDWeb. Paste that value into the modal and login using your username and password. You can now run this query:

1query {
2 me {
3 Username
4 UserStatus
5 UserCreateDate
6 UserAttributes {
7 Name
8 Value
9 }
10 MFAOptions {
11 AttributeName
12 DeliveryMedium
13 }
14 Enabled
15 PreferredMfaSetting
16 UserMFASettingList
17 UserLastModifiedDate
18 }
19}

which will return user information related to the current user directly from your user pool.

Structure of the function event

When writing lambda functions that are connected via the @function directive, you can expect the following structure for the AWS Lambda event object.

KeyDescription
typeNameThe name of the parent object type of the field being resolver.
fieldNameThe name of the field being resolved.
argumentsA map containing the arguments passed to the field being resolved.
identityA map containing identity information for the request. Contains a nested key 'claims' that will contains the JWT claims if they exist.
sourceWhen resolving a nested field in a query, the source contains parent value at runtime. For example when resolving Post.comments, the source will be the Post object.
requestThe AppSync request object. Contains header information.
prevWhen using pipeline resolvers, this contains the object returned by the previous function. You can return the previous value for auditing use cases.

Your function should follow the lambda handler guidelines for your specific language. See the developer guides from the AWS Lambda documentation for your chosen language. If you choose to use structured types, your type should serialize the AWS Lambda event object outlined above. For example, if using Golang, you should define a struct with the above fields.

Calling functions in different regions

By default, you expect the function to be in the same region as the amplify project. If you need to call a function in a different (or static) region, you can provide the region argument.

1type Query {
2 echo(msg: String): String @function(name: "echofunction", region: "us-east-1")
3}

Calling functions in different AWS accounts is not supported via the @function directive but is supported by AWS AppSync.

Chaining functions

The @function directive supports AWS AppSync pipeline resolvers. That means, you can chain together multiple functions such that they are invoked in series when your field's resolver is invoked. To create a pipeline resolver that calls out to multiple AWS Lambda functions in series, use multiple @function directives on the field.

1type Mutation {
2 doSomeWork(msg: String): String
3 @function(name: "worker-function")
4 @function(name: "audit-function")
5}

In the example above when you run a mutation that calls the Mutation.doSomeWork field, the worker-function will be invoked first then the audit-function will be invoked with an event that contains the results of the worker-function under the event.prev.result key. The audit-function would need to return event.prev.result if you want the result of worker-function to be returned for the field. Under the hood, Amplify creates an AppSync::FunctionConfiguration for each unique instance of @function in a document and a pipeline resolver containing a pointer to a function for each @function on a given field.

Generates

The @function directive generates these resources as necessary:

  1. An AWS IAM role that has permission to invoke the function as well as a trust policy with AWS AppSync.
  2. An AWS AppSync data source that registers the new role and existing function with your AppSync API.
  3. An AWS AppSync pipeline function that prepares the lambda event and invokes the new data source.
  4. An AWS AppSync resolver that attaches to the GraphQL field and invokes the new pipeline functions.