AWS Appsync Subscription with CDK and without Amplify

276 Views Asked by At

How can I create an AppSync Subscription with AWS CDK? I am able to successfully create Queries and Mutations, but I'm having trouble with Subscriptions. Is it possible? If so, how can I achieve it?

This is how I'm currently attempting it:

cdk:

const projectAddedSubscription = new appsync.Resolver(this, 'ProjectAddedSubscription', {
      api: api,
      typeName: 'Subscription',
      fieldName: 'onCreateProject',
      dataSource: appDbDataSource,
      requestMappingTemplate: appsync.MappingTemplate.fromFile('appsync/resolvers/request/onCreateProjectRequest.vtl'),
      responseMappingTemplate: appsync.MappingTemplate.fromFile('appsync/resolvers/response/onCreateProjectResponse.vtl')
});

GraphQL:

type Project {
    PK: ID!
    SK: ID!
    name: String!
    createdAt: String!
    createdBy: String!
}


type Mutation {
    createProject(input: CreateProjectInput!): CreateProjectResponse!
}

type Subscription {
    onCreateProject: Project
}

request VTL:

    {
  "version": "2018-05-29",
  "operation": "Subscription",
  "payload": {
    "field": "onCreateProject"
  }
}

response VTL:

#if($ctx.error)
  $util.error($ctx.error.message, $ctx.error.type)
#else
  $util.toJson($ctx.result.data.onCreateProject)
#end
1

There are 1 best solutions below

0
On

The solution was that there was no need to write a Resolver for it, and no VTL is required. The trigger needs to be specified in the GraphQL schema.

type Subscription {
    onCreateProject: CreateProjectResponse
    @aws_subscribe(mutations: ["createProject"])
}

I didn't know that AppSync supports this out of the box, and the IDE doesn't recognize it either, but it still works nevertheless.

enter image description here