Skip to content

Example for AppSync subscription resolver to work

0

Hi I was not able to make a working subscription resolver for my subscription field.

The sample schema is as follows:

type Message {
  user: String!
  body: String!
}

type Mutation {
  pushMessage(user: String!, body: String!): Message
}

type Query {
  	getMessages(user: String!): [Message]
}

type Subscription {
  onMessage(user: String!): Message @aws_subscribe(mutations: ["pushMessage"])
}

By referencing https://docs.aws.amazon.com/appsync/latest/devguide/security-authorization-use-cases.html#security-real-time-data, I was able to write

import { util } from '@aws-appsync/utils';

export function request(ctx) {
  const {identity, args} = ctx
  if (!!(identity?.resolverContext?.user)) {
    if (identity.resolverContext.user != args.user) {
      util.unauthorized()
    }
  }
  return {}
}

export function response(ctx) {
  return {}
}

as my resolver.

P.S I used the lambda authorization method to carry custom resolverContext to the ctx.

However, this did not work.

Can anyone give a robust example of how a subscription resolver can work? The official documentation has some flaws btw.

example errors from real-time websocket message

  "type": "error",
  "payload": {
    "errors": [
      {
        "errorType": "Code",
        "message": "Value for field '$[operation]' not found."
      }
    ]
  }

or

.... null, request resource not match , something like that
asked a year ago384 views
1 Answer
1
Accepted Answer

I found the solution,

As I am using data directly from the lambda resolver's context and the context arguments only, there is no need for other Dynamodb data source to be bound. So I switch to NoneDataSource and have the following, then it works.

import { util } from '@aws-appsync/utils';

export function request(ctx) {
  return {
payload: ctx.args
}
}

export function response(ctx) {
    const {identity, args} = ctx
  if (!!(identity?.resolverContext?.user)) {
    if (identity.resolverContext.user != args.user) {
     return util.unauthorized()
    }
  }
}

As you can see, the request needs to comply with the data source format, the payload field must be specified for the NoneDataSource (good for just passing data), while the version and operation fields, etc need to be specified for the Dynamodb data source. That was why my resolver for the subscription did not work.

answered a year ago
EXPERT
reviewed a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.