In GraphQL, a resolver is a function that gets the arguments and the context for a field and returns a value. This is a generic concept and applies to all GraphQL servers. But how this function is implemented, such as what language it can be written in, can be different between servers.
In AppSync, a resolver is broken into three parts:
The code contains two function: the request and the response functions. To resolve a field, first the request function converts the GraphQL context into a format suitable for the data source. Then the data source interacts with some external service, such as a database, a Lambda function, or sends an HTTP request. Then the response function gets the result of the data source and converts it into a format suitable for the resolver's result.
The resolver code is written in a constrained version of Javascript. It supports most of the basics of the language but is only suitable for short scripts. For example, it must be synchronous and can't use Promises. Moreover, it can't include libraries and its runtime is limited to a few milliseconds.
For example, to get an item from a DynamoDB table, the request function for the groupById
resolver can use the id
argument:
export function request(ctx) {
return {
version: "2018-05-29",
operation: "GetItem",
key: {
id: {S: ctx.args.id}
}
}
}
When a query comes for this field, such as this one:
query MyQuery {
groupById(id: "group1") {
id
name
}
}
The result object will be:
{
version: "2018-05-29",
operation: "GetItem",
key: {
id: {S: "group1"}
}
}
The DynamoDB data source knows how to process this input, and fetches an item from the configured table with the id
of group1
.
Then the response function needs to convert the item to the resolver's result format:
export function response(ctx) {
if (ctx.error) {
return util.error(ctx.error.message, ctx.error.type);
}
return ctx.result;
}