Prototyping Queries in AWS AppSync

Subscribe to my newsletter and never miss my upcoming articles

Did you know there's a simple way to create mock responses for AWS AppSync queries? To accomplish this you just need to create the query, a special data source, and a resolver.

Define the Query

To keep things simple, we're going to be prototyping the following graphql query.

type Query {
  foo(input: FooInput): FooOutput!
}

type FooOutput {
  bar: String!
}

input FooInput {
  value: Int
}

Create the Data Source

We'll be using a special passthrough data source type, aptly named NONE. Here's all that's required to make it in CDK.

const prototypeDS = graphqlApi.addNoneDataSource(`prototypeDataSource`, {
      name: "Prototype",
      description: "Prototype graphql responses"
    });

VTL Templates

The vtl request template is going to be the same for all of your prototype requests.

{
    "version": "2018-05-29",
    "payload": $util.toJson($ctx.args.input)
}

Finally, the fun part. We can define the response by modifying the content within $util.Json in the following template.

#set($value = $ctx.args.input.value)

$util.toJson({
  "bar": "You entered ${value}"
})

Creating the Resolver

Now that we have a query, data source, and some vtl templates it's time to tie them all together with a resolver.

prototypeDS.createResolver({
      typeName: "Query",
      fieldName: "foo",
      requestMappingTemplate: appsync.MappingTemplate.fromFile(join(__dirname, "mapping-templates", "Query.foo.request.vtl")),
      responseMappingTemplate: appsync.MappingTemplate.fromFile(join(__dirname, "mapping-templates", "Query.foo.response.vtl"))
    });

Testing

All that's left to do is deploy the stack and try out the new query

query {
  foo(input: { value: 12 }) {
    bar
  }
}

You should get back

{
  "data": {
    "foo": {
      "bar": "You entered 12"
    }
  }
}

Summary

You've seen how to easily prototype responses to a query so that frontend developers can start working without waiting for the backend to be fully implemented. You can use this decoupling to allow your frontend and backend developers to work concurrently, or let the frontend devs start first so they can identify any issues with the query before wasting time on the backend.


References

Backdrop photo by Photo by Sigmund on Unsplash

No Comments Yet