Useful AWS AppSync GraphQL Utility Helpers you might not know about
AWS AppSync is a managed serverless GraphQL service that simplifies application development by letting you create a flexible API to securely access, manipulate, and combine data from one or more data sources with a single network call.
With GraphQL, special functions called Resolvers are used to implement business logic linking or “resolving” types, fields, or operations defined in the GraphQL schema with the data in data sources such as Amazon DynamoDB, AWS Lambda, HTTP APIs, and more. Resolvers provide the runtime to fulfill GraphQL operations such as queries, mutations, or subscriptions with the right data.
AppSync leverages VTL or Apache Velocity Templates to provide a lean and fast compute layer to resolve GraphQL queries or fields. Alternatively developers can use any language or runtime in AppSync with Direct Lambda Resolvers.
AppSync uses VTL to translate GraphQL requests from clients into a request to your data source. Then it reverses the process to translate the data source response back into a GraphQL response. VTL Resolvers are comprised of request and response mapping templates, which contain transformation and execution logic.
There are several advantages to using VTL templates in AppSync:
- VTL templates allow you to separate and customize business, transformation, and execution logic at different stages in the API call, either before it reaches the data source for the request or after the data is retrieved in the response. Think of them as lifecycle hooks for the API call itself.
- As a logical templating language, VTL allows you to set default values for new items, transform and shape data, iterate over lists, maps, and arrays, filter or change responses based on the user identity.
- With VTL in AppSync developers can configure batching for Lambda or DynamoDB as well as DynamoDB transactions.
- VTL resolvers are managed internally by AppSync. For simple business logic there’s no need to deploy extra AWS compute services/resources in your account.
- Low latency and no cold starts
VTL Resolvers in AppSync provide built-in flexible integrated utilities that allow developers to simplify interactions with data from data sources. By using these utilities (including three brand new ones) there is no need to create your own logic to perform specific tasks such as:
1. Automatically generate identifiers:
AppSync can automatically generate different types of identifiers when working with ID fields in a GraphQL type. While UUID are general use unique identifiers, ULIDs and KSULIDs are sortable using built-in timestamps. Very useful when you need to automatically generate primary keys for objects in a data source.
$util.autoId(): Automatically generates a UUID (Universally Unique IDentifier) for a specific field.
$util.autoUlid(): Automatically generates a ULID (Universally Unique Lexicographically Sortable IDentifier) for a specific field.
$util.autoKsuid(): Automatically generates a KSUID (K-Sortable Unique IDentifier) for a specific field. (NEW!)
2. Work with JSON objects:
$util.parseJson(): Converts a string to JSON.
$util.toJson(): Converts JSON to a string.
3. Define authorization logic:
You can use the following utilities to help define authorization business logic when resolving a field or executing a GraphQL operation in AppSync.
$util.unauthorized(): Throws an
Unauthorizederror for the field being resolved. Use this in request or response mapping templates to determine whether to allow the caller to resolve the field.
$util.authType(): Describe the authorization type being used by a request, returning back either “IAM Authorization”, “Lambda Authorization”, “User Pool Authorization”, “Open ID Connect Authorization”, or “API Key Authorization”. Useful when implementing multiple authorization modes in a single AppSync API.
4. Sort data:
When retrieving a list of results from a data source, AppSync can automatically sort the list based on specific conditions. This utility can sort lists of up to 1000 objects.
$util.list.sortList(): Sorts a list of objects, in ascending or descending order, based on a specific field used for sorting.
5. Test, log and debug your resolver logic:
You can send informational (i.e. a Tenant ID) or error data to CloudWatch Logs directly from your resolver code.
$util.log.info(): Logs an informational string or object value to the request log stream when either request-level or field-level CloudWatch logging is enabled with log level ALL on the API. (NEW!)
$util.log.error(): Logs an error string or object value to the request log stream when field-level CloudWatch logging is enabled with log level ERROR or log level ALL on the API. (NEW!)
6. Work with HTTP headers:
Sometimes applications need to be aware of specific HTTP headers sent from clients, other times the application needs to generate specific response headers to clients depending on specific conditions. AppSync can do all of it directly from the GraphQL API itself.
$util.http.copyHeaders(): Generally used to forward request headers to a downstream HTTP endpoint.
$util.http.addResponseHeaders(): Generate or forwards specific HTTP response headers to clients.
7. Encode and decode:
With these AppSync utilities it’s easy to encode or decode URLs or base64 strings automatically.
$util.urlEncode(): Returns the input string as an
$util.urlDecode(): Decodes an
application/x-www-form-urlencodedencoded string back to its non-encoded form.
$util.base64Encode(): Encodes the input into a base64-encoded string.
$util.base64Decode(): Decodes the data from a base64-encoded string.
8. Work with XML:
If you work with a legacy application that uses XML, AppSync has you covered. You can use utilities to convert XML to JSON.
$util.xml.toJsonString(): Converts an XML string to a JSON string. Useful if you want to directly convert and return the XML response from an HTTP object to JSON.
$util.xml.toMap(): Converts an XML string to a JSON Dictionary.
9. Interact with Amazon DynamoDB:
AppSync provides first-class support to interact with DynamoDB NoSQL tables. You can use different helper methods that make it easier to write and read data to Amazon DynamoDB, such as automatic type mapping and formatting. These methods are designed to make mapping primitive types and lists to the proper DynamoDB input format automatically. There are several different utilities in this category, we just list a few here:
$util.dynamodb.toDynamoDB(): General object conversion tool for DynamoDB that converts input objects to the appropriate DynamoDB representation.
$util.dynamodb.toMapValuesJson(): Converts all arguments in an GraphQL operation to its appropriate DynamoDB format. Useful when creating or updating multiple fields related to a specific primary key object in DynamoDB.
$util.dynamodb.toList(): Converts a list of object to DynamoDB list format. Each item in the list is also converted to its appropriate DynamoDB format.
$util.dynamodb.toS3Object(): Converts the key, bucket and region into the DynamoDB S3 Object representation.
$util.transform.toDynamoDBFilterExpression(): Converts an input string to a filter expression for use with DynamoDB.
10. Simplify how to filter data from and to real-time clients
Enhanced real-time subscriptions filtering in AppSync allow developers can create real-time experiences in their applications by leveraging extra logical operators, server-side filtering, and the ability to trigger subscription invalidations. AppSync can use a handy utility to define filters and conditions based on client requests:
$util.transform.toSubscriptionFilter(): Converts a simplified input object to a filter expression object. It allows clients to define enhanced filters to interact with real-time data and control what should be received.
These are my personal favorite AppSync GraphQL utility helpers. What are yours? What more utilities would you like to see in AppSync in the future? Let us know by leaving comments bellow. For more information about GraphQL utility helpers in Appsync, refer to the documentation.