Aws appsync resolver

Aws appsync resolver DEFAULT

Tutorial: Local Resolvers

AWS AppSync allows you to use supported data sources (AWS Lambda, Amazon DynamoDB, or Amazon OpenSearch Service) to perform various operations. However, in certain scenarios, a call to a supported data source might not be necessary.

This is where the local resolver comes in handy. Instead of calling a remote data source, the local resolver will just forward the result of the request mapping template to the response mapping template. The field resolution will not leave AWS AppSync.

Local resolvers are useful for several use cases. The most popular use case is to publish notifications without triggering a data source call. To demonstrate this use case, let’s build a paging application; where users can page each other. This example leverages Subscriptions, so if you aren’t familiar with Subscriptions, you can follow the Real-Time Data tutorial.

Create the Paging Application

In our paging application, clients can subscribe to an inbox, and send pages to other clients. Each page includes a message. Here is the schema:

Let’s attach a resolver on the field. In the Schema pane, click on Attach Resolver next to the field definition on the right panel. Create a new data source of type None and name it PageDataSource.

For the request mapping template, enter:

And for the response mapping template, select the default Forward the result. Save your resolver. You application is now ready, let’s page!

Send and subscribe to pages

For clients to receive pages, they must first be subscribed to an inbox.

In the Queries pane let’s execute the subscription:

Nadia will receive pages whenever the mutation is invoked. Let’s invoke the mutation by executing the mutation:

We just demonstrated the use of local resolvers, by sending a Page and receiving it without leaving AWS AppSync.

Document Conventions

Tutorial: Amazon OpenSearch Service Resolvers

Tutorial: Combining GraphQL Resolvers

Sours: https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-local-resolvers.html

Resolver

cachingConfig

The caching configuration for the resolver.

Type: CachingConfig object

Required: No

dataSourceName

The resolver data source name.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 65536.

Pattern:

Required: No

fieldName

The resolver field name.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 65536.

Pattern:

Required: No

kind

The resolver type.

  • UNIT: A UNIT resolver type. A UNIT resolver is the default resolver type. A UNIT resolver enables you to execute a GraphQL query against a single data source.

  • PIPELINE: A PIPELINE resolver type. A PIPELINE resolver enables you to execute a series of in a serial manner. You can use a pipeline resolver to execute a GraphQL query against multiple data sources.

Type: String

Valid Values:

Required: No

pipelineConfig

The .

Type: PipelineConfig object

Required: No

requestMappingTemplate

The request mapping template.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 65536.

Required: No

resolverArn

The resolver ARN.

Type: String

Required: No

responseMappingTemplate

The response mapping template.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 65536.

Required: No

syncConfig

The for a resolver attached to a versioned datasource.

Type: SyncConfig object

Required: No

typeName

The resolver type name.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 65536.

Pattern:

Required: No

Sours: https://docs.aws.amazon.com/appsync/latest/APIReference/API_Resolver.html
  1. Ubnt app
  2. Watch wiseguy
  3. Urban wall art decor
  4. Invesco shipping etf
  5. Sr contracts administrator salary

AWS::AppSync::Resolver

The resource defines the logical GraphQL resolver that you attach to fields in a schema. Request and response templates for resolvers are written in Apache Velocity Template Language (VTL) format. For more information about resolvers, see Resolver Mapping Template Reference.

Note

When you submit an update, AWS CloudFormation updates resources based on differences between what you submit and the stack's current template. To cause this resource to be updated you must change a property value for this resource in the CloudFormation template. Changing the Amazon S3 file content without changing a property value will not result in an update operation.

See Update Behaviors of Stack Resources in the AWS CloudFormation User Guide.

Syntax

To declare this entity in your AWS CloudFormation template, use the following syntax:

JSON

Properties

The AWS AppSync GraphQL API to which you want to attach this resolver.

Required: Yes

Type: String

Update requires: Replacement

The caching configuration for the resolver.

Required: No

Type: CachingConfig

Update requires: No interruption

The resolver data source name.

Required: No

Type: String

Update requires: No interruption

The GraphQL field on a type that invokes the resolver.

Required: Yes

Type: String

Update requires: Replacement

The resolver type.

  • UNIT: A UNIT resolver type. A UNIT resolver is the default resolver type. A UNIT resolver enables you to execute a GraphQL query against a single data source.

  • PIPELINE: A PIPELINE resolver type. A PIPELINE resolver enables you to execute a series of in a serial manner. You can use a pipeline resolver to execute a GraphQL query against multiple data sources.

Required: No

Type: String

Update requires: No interruption

Functions linked with the pipeline resolver.

Required: No

Type: PipelineConfig

Update requires: No interruption

The request mapping template.

Request mapping templates are optional when using a Lambda data source. For all other data sources, a request mapping template is required.

Required: No

Type: String

Update requires: No interruption

The location of a request mapping template in an Amazon S3 bucket. Use this if you want to provision with a template file in Amazon S3 rather than embedding it in your CloudFormation template.

Required: No

Type: String

Update requires: No interruption

The response mapping template.

Required: No

Type: String

Update requires: No interruption

The location of a response mapping template in an Amazon S3 bucket. Use this if you want to provision with a template file in Amazon S3 rather than embedding it in your CloudFormation template.

Required: No

Type: String

Update requires: No interruption

The for a resolver attached to a versioned datasource.

Required: No

Type: SyncConfig

Update requires: No interruption

The GraphQL type that invokes this resolver.

Required: Yes

Type: String

Update requires: Replacement

Return values

Ref

When you pass the logical ID of an resource to the intrinsic function, the function returns the ARN of the Resolver, such as .

For more information about using the function, see Ref.

Fn::GetAtt

returns a value for a specified attribute of this type. The following are the available attributes and sample return values.

For more information about using , see Fn::GetAtt.

The GraphQL field on a type that invokes the resolver.

ARN of the resolver, such as .

The GraphQL type that invokes this resolver.

Examples

Resolver Creation Example

The following example creates a resolver and associates it with an existing GraphQL API and a data source by passing the GraphQL API ID and data source name as a parameter.

YAML

JSON

See also

Sours: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appsync-resolver.html
AWS re:Invent 2019: Develop serverless GraphQL architectures using AWS AppSync (MOB309-R1)

Resolver Mapping Template Context Reference

AWS AppSync defines a set of variables and functions for working with resolver mapping templates. This makes logical operations on data easier with GraphQL. This document describes those functions and provides examples for working with templates.

Accessing the

The variable is a map that holds all of the contextual information for your resolver invocation. It has the following structure:

Note: If you’re trying to access a dictionary/map entry (such as an entry in ) by its key to retrieve the value, the Velocity Template Language (VTL) allows for you to directly use the notation . However, this might not work for all cases, such as when the key names have special characters (for example, an underscore “_”). We recommend that you always use notation.

Each field in the map is defined as follows:

A map that contains all GraphQL arguments for this field.

An object that contains information about the caller. For more information about the structure of this field, see Identity.

A map that contains the resolution of the parent field.

The stash is a map that is made available inside each resolver and function mapping template. The same stash instance lives through a single resolver execution. This means that you can use the stash to pass arbitrary data across request and response mapping templates, and across functions in a pipeline resolver. The stash exposes the same methods as the Java Map data structure.

A container for the results of this resolver. This field is only available to response mapping templates.

For example, if you’re resolving the field of the following query:

Then the full variable that is available when processing a response mapping template might be:

It represents the result of whatever previous operation was executed in a pipeline resolver. If the previous operation was the pipeline resolver request mapping template, then represents the output of the evaluation of the template, and is made available to the first function in the pipeline. If the previous operation was the first function, then represents the output of the first function, and is made available to the second function in the pipeline. If the previous operation was the last function, then represents the output of the first function, and is made available to the pipeline resolver response mapping template.

An object that contains information about the GraphQL request. For the structure of this field, see Info.

Identity

The section contains information about the caller. The shape of this section depends on the authorization type of your AWS AppSync API.

For more information about this section and how it can be used, see Security.

authorization

The field isn’t populated.

authorization

The contains the key, containing the same content returned by the Lambda function authorizing the request.

authorization

The has the following shape:

authorization

The has the following shape:

Each field is defined as follows:

The AWS account ID of the caller.

The claims that the user has.

Either authenticated or unauthenticated based on the identity type.

A comma separated list of external identity provider information used in obtaining the credentials used to sign the request.

The Amazon Cognito identity ID of the caller.

The Amazon Cognito identity pool ID associated with the caller.

The default authorization strategy for this caller ( or ).

The token issuer.

The source IP address of the caller received by AWS AppSync. If the request doesn’t include the header, the source IP value contains only a single IP address from the TCP connection. If the request includes a header, the source IP is a list of IP addresses from the header, in addition to the IP address from the TCP connection.

The UUID of the authenticated user.

The IAM user.

The ARN of the IAM user.

The user name of the authenticated user. In the case of authorization, the value of username is the value of attribute cognito:username. In the case of authorization, the value of username is the value of the AWS user principal. We recommend that you use if you’re using IAM authorization with credentials vended from Amazon Cognito identity pools.

Access Request Headers

AWS AppSync supports passing custom headers from clients and accessing them in your GraphQL resolvers by using . You can then use the header values for actions like inserting data to a data source or even authorization checks. Single or multiple request headers can be used, as shown in the following examples using with an API key from the command line:

Single Header Example

Suppose you set a header of with a value of like the following:

This could then be accessed with . For example, it might be in the following VTL for DynamoDB:

Multiple Header Example

You can also pass multiple headers in a single request and access these in the resolver mapping template. For example, if the header was set with two values:

You could then access these as an array, such as .

Note: AWS AppSync doesn’t expose the cookie header in .

Info

The section contains information about the GraphQL request.

The has the following shape:

Each field is defined as follows:

The name of the field that is currently being resolved.

The name of the parent type for the field that is currently being resolved.

A map which holds all variables that are passed into the GraphQL request.

A list representation of the fields in the GraphQL selection set. Fields that are aliased will only be referenced by the alias name, not the field name. The following example shows this in detail.

A string representation of the selection set, formatted as GraphQL schema definition language (SDL). Although fragments aren’t be merged into the selection set, inline fragments are preserved, as shown in the following example.

Note: When using on , the values returned by and will not be serialized by default.

For example, if you are resolving the field of the following query:

Then the full variable that is available when processing a mapping template might be:

Note: only exposes fields that belong to the current type. If the current type is an interface or union, only selected fields that belong to the interface will be exposed. For example, given the following schema:

and query:

When calling at the field resolution, only will be exposed:

Sanitizing inputs

Applications must sanitize untrusted inputs to prevent any external party from using an application outside of its intended use. As the contains user inputs in properties such as , , , and , care must be taken to sanitize their values in mapping templates.

Since mapping templates represent JSON, input sanitization takes the form of escaping JSON reserved characters from strings that represent user inputs. It is best practice to use the utility to escape JSON reserved characters from sensitive string values when placing them into a mapping template.

For example, in the Lambda request mapping template below, because we accessed an unsafe customer input string (), we wrapped it with to prevent unescaped JSON characters from breaking the JSON template.

As opposed to the mapping template below, where we insert directly without sanitization. This will not work for strings containing unescaped double quotes or other JSON reserved characters and may leave your template open to failure.

Document Conventions

Resolver Mapping Template Programming Guide

Resolver mapping template utility reference

Sours: https://docs.aws.amazon.com/appsync/latest/devguide/resolver-context-reference.html

Resolver aws appsync

Tutorial: HTTP Resolvers

AWS AppSync enables you to use supported data sources (that is, AWS Lambda, Amazon DynamoDB, Amazon OpenSearch Service, or Amazon Aurora) to perform various operations, in addition to any arbitrary HTTP endpoints to resolve GraphQL fields. After your HTTP endpoints are available, you can connect to them using a data source. Then, you can configure a resolver in the schema to perform GraphQL operations such as queries, mutations, and subscriptions. This tutorial walks you through some common examples.

In this tutorial you use a REST API (created using Amazon API Gateway and Lambda) with an AWS AppSync GraphQL endpoint.

One-Click Setup

If you want to automatically set up a GraphQL endpoint in AWS AppSync with an HTTP endpoint configured (using Amazon API Gateway and Lambda), you can use the following AWS CloudFormation template :

Creating a REST API

You can use the following AWS CloudFormation template to set up a REST endpoint that works for this tutorial:

The AWS CloudFormation stack performs the following steps:

  1. Sets up a Lambda function that contains your business logic for your microservice.

  2. Sets up an API Gateway REST API with the following endpoint/method/content type combination:

API Resource PathHTTP MethodSupported Content Type

/v1/users

POST

application/xml

/v1/users/1

GET

application/json

/v1/users/1

PUT

application/json

/v1/users/1

DELETE

application/json

Creating Your GraphQL API

To create the GraphQL API in AWS AppSync:

  • Open the AWS AppSync console and choose Create API.

  • For the API name, type .

  • Choose Custom schema.

  • Choose Create.

The AWS AppSync console creates a new GraphQL API for you using the API key authentication mode. You can use the console to set up the rest of the GraphQL API and run queries on it for the remainder of this tutorial.

Creating a GraphQL Schema

Now that you have a GraphQL API, let’s create a GraphQL schema. From the schema editor in the AWS AppSync console, make sure you schema matches the following schema:

Configure Your HTTP Data Source

To configure your HTTP data source, do the following:

  • On the DataSources tab, choose New, and then type a friendly name for the data source (for example, ).

  • In Data source type, choose HTTP.

  • Set the endpoint to the API Gateway endpoint that is created. Make sure that you don’t include the stage name as part of the endpoint.

Note: At this time only public endpoints are supported by AWS AppSync.

Note: For more information about the certifying authorities that are recognized by the AWS AppSync service, see Certificate Authorities (CA) Recognized by AWS AppSync for HTTPS Endpoints.

Configuring Resolvers

In this step, you connect the http data source to the getUser query.

To set up the resolver:

  • Choose the Schema tab.

  • In the Data types pane on the right under the Query type, find the getUser field and choose Attach.

  • In Data source name, choose HTTP.

  • In Configure the request mapping template, paste the following code:

  • In Configure the response mapping template, paste the following code:

  • Choose the Query tab, and then run the following query:

This should return the following response:

  • Choose the Schema tab.

  • In the Data types pane on the right under Mutation, find the addUser field and choose Attach.

  • In Data source name, choose HTTP.

  • In Configure the request mapping template, paste the following code:

  • In Configure the response mapping template, paste the following code:

  • Choose the Query tab, and then run the following query:

This should return the following response:

Invoking AWS Services

You can use HTTP resolvers to set up a GraphQL API interface for AWS services. HTTP requests to AWS must be signed with the Signature Version 4 process so that AWS can identify who sent them. AWS AppSync calculates the signature on your behalf when you associate an IAM role with the HTTP data source.

You provide two additional components to invoke AWS services with HTTP resolvers:

  • An IAM role with permissions to call the AWS service APIs

  • Signing configuration in the data source

For example, if you want to call the ListGraphqlApis operation with HTTP resolvers, you first create an IAM role that AWS AppSync assumes with the following policy attached:

Next, create the HTTP data source for AWS AppSync. In this example, you call AWS AppSync in the US West (Oregon) Region. Set up the following HTTP configuration in a file named , which includes the signing region and service name:

Then, use the AWS CLI to create the data source with an associated role as follows:

When you attach a resolver to the field in the schema, use the following request mapping template to call AWS AppSync:

When you run a GraphQL query for this data source, AWS AppSync signs the request using the role you provided and includes the signature in the request. The query returns a list of AWS AppSync GraphQL APIs in your account in that AWS Region.

Sours: https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-http-resolvers.html
Testing AWS AppSync Resolvers

Resolver tutorials

Data sources and resolvers are how AWS AppSync translates GraphQL requests and fetches information from your AWS resources. AWS AppSync has support for automatic provisioning and connections with certain data source types. AWS AppSync supports AWS Lambda, Amazon DynamoDB, relational databases (Amazon Aurora Serverless), Amazon OpenSearch Service, and HTTP endpoints as data sources. You can use a GraphQL API with your existing AWS resources or build data sources and resolvers. This section takes you through this process in a series of tutorials for better understanding how the details work and tuning options.

AWS AppSync uses mapping templates written in Apache Velocity Template Language (VTL) for resolvers. For more information about using mapping templates, see the Resolver mapping template reference. More information about working with VTL is available in the Resolver mapping template programming guide.

AWS AppSync supports the automatic provisioning of DynamoDB tables from a GraphQL schema as described in (Optional) Provision from Schema and Launch a Sample Schema. You can also import from an existing DynamoDB table which will create schema and connect resolvers. This is outlined in (Optional) Import from Amazon DynamoDB.

Sours: https://docs.aws.amazon.com/appsync/latest/devguide/tutorials.html

Now discussing:

Pipeline Resolvers

AWS AppSync executes resolvers on a GraphQL field. In some cases, applications require executing multiple operations to resolve a single GraphQL field. With pipeline resolvers, developers can now compose operations (called Functions) and execute them in sequence. Pipeline resolvers are useful for applications that, for instance, require performing an authorization check before fetching data for a field.

Anatomy of a pipeline resolver

A pipeline resolver is composed of a Before mapping template, an After mapping template, and a list of Functions. Each Function has a request and response mapping template that it executes against a Data Source. As a pipeline resolver delegates execution to a list of functions, it is therefore not linked to any data source. Unit resolvers and functions are primitives that execute operation against data sources. See the Resolver Mapping Template Overview for more information.

Before Mapping template

The request mapping template of a pipeline resolver or also called the Before step, allows to perform some preparation logic before executing the defined functions.

Functions list

The list of functions a pipeline resolver will run in sequence. The pipeline resolver request mapping template evaluated result is made available to the first function as . Each function output is available to the next function as .

After mapping template

The response mapping template of a pipeline resolver or also called the After step, allows to perform some final mapping logic from the output of the last function to the expected GraphQL field type. The output of the last function in the functions list is available in the pipeline resolver mapping template as or .

Execution Flow

Given a pipeline resolver comprised of 2 functions, the list below represents the execution flow when the resolver is invoked:

  1. Pipeline resolver BEFORE mapping template

  2. Function 1: Function request mapping template

  3. Function 1: Data source invocation

  4. Function 1: Function response mapping template

  5. Function 2: Function request mapping template

  6. Function 2: Data source invocation

  7. Function 2: Function response mapping template

  8. Pipeline resolver AFTER mapping template

Pipeline resolver execution flow is unidirectional and defined statically on the resolver.

Useful Apache Velocity Template Language (VTL) Utilities

As the complexity of an application increases, VTL utilities and directives are here to facilitate development productivity. The following utilities can help you when you’re working with pipeline resolvers.

$ctx.stash

The stash is a Map that is made available inside each resolver and function mapping template. The same stash instance lives through a single resolver execution. What this means is you can use the stash to pass arbitrary data across request and response mapping templates, and across functions in a pipeline resolver. The stash exposes the same methods as the Java Map data structure.

$ctx.prev.result

The represents the result of the previous operation that was executed in the pipeline. If the previous operation was the pipeline resolver request mapping template, then represents the output of the evaluation of the template and is made available to the first function in the chain. If the previous operation was the first function, then represents the output of the first function and is made available to the second function in the pipeline. If the previous operation was the last function, then represents the output of the last function and is made available to the pipeline resolver response mapping template.

#return(data: Object)

The directive comes handy if you need to return prematurely from any mapping template. is analogous to the return keyword in programming languages because it returns from the closest scoped block of logic. What this means is that using inside a resolver mapping template returns from the resolver. Using in a resolver mapping template sets on the GraphQL field. Additionally, using from a function mapping template returns from the function and continues the execution to either the next function in the pipeline or the resolver response mapping template.

#return

Same as but will be returned instead.

$util.error

The utility is useful to throw a field error. Using inside a function mapping template throws a field error immediately, which prevents subsequent functions from being executed. For more details and other signatures, visit the Resolver Mapping Template Utility Reference.

$util.appendError

The is similar to the , with the major distinction that it doesn’t interrupt the evaluation of the mapping template. Instead, it signals there was an error with the field, but allows the template to be evaluated and consequently return data. Using inside a function will not disrupt the execution flow of the pipeline. For more details and other signatures, visit the Resolver Mapping Template Utility Reference.

Create A Pipeline Resolver

In the AWS AppSync console, go to the Schema page.

Save the following schema:

We are going to wire a pipeline resolver to the signUp field on the Mutation type. In the Mutation type on the right side, choose Attach resolver next to the field. On the Create Resolver page, click on the Switch to Pipeline button. The page should now show 3 sections, a Before Mapping Template text area, a Functions section, and a After Mapping template text area.

Our pipeline resolver signs up a user by first validating the email address input and then saving the user in the system. We are going to encapsulate the email validation inside a validateEmail function, and the saving of the user inside a saveUser function. The validateEmail function executes first, and if the email is valid, then the saveUser function executes.

The execution flow will be as follow:

  1. Mutation.signUp resolver request mapping template

  2. validateEmail function

  3. saveUser function

  4. Mutation.signUp resolver response mapping template

Because we will probably reuse the validateEmail function in other resolvers on our API, we want to avoid accessing since these will change from one GraphQL field to another. Instead, we can use the to store the email attribute from the input field argument.

BEFORE mapping template:

The console provides a default passthrough AFTER mapping template that will we use:

Create A Function

From the pipeline resolver page, on the Functions section, click on Create Function. It is also possible to create functions without going through the resolver page, to do this, in the AWS AppSync console, go to the Functions page. Choose the Create Function button. Let’s create a function that checks if an email is valid and comes from a specific domain. If the email is not valid, the function raises an error. Otherwise, it forwards whatever input it was given.

Select NONE data source on the function page, and fill in the validateEmail request mapping template:

and response mapping template:

We just created our validateEmail function. Repeat these steps to create the saveUser function with the following request and response mapping templates. For the sake of simplicity we use a NONE data source and pretend the user has been saved in the system after the function executes.

Request mapping template:

and response mapping template:

We just created out saveUser function.

Adding a Function to a Pipeline Resolver

Our functions should have been automatically added to the pipeline resolver we just created. If you happened to have created the functions through the console Functions page, you can click on Add Function on the resolver page to attach them. Add both validateEmail and saveUser functions to the resolver. The validateEmail function should be placed before the saveUser function. As you add more functions you can use the up and down arrows to reorganize the order of execution of your functions.

Executing a Query

In the AWS AppSync console, go to the Queries page. Enter the following query:

should return something like:

We have successfully signed up our user and validated the input email using a pipeline resolver. To follow a more complete tutorial focusing on pipeline resolvers, you can go to Tutorial: Pipeline Resolvers

Sours: https://docs.aws.amazon.com/appsync/latest/devguide/pipeline-resolvers.html


1081 1082 1083 1084 1085