Subscriptions

In addition to queries and muations, you can leverage your Sqlmancer client for resolving subscriptions as well. Here's a simple example for a mutation that creates a Customer record:

const typeDefs = gql`
type Mutation {
createCustomer: Customer @input
}
type Subscription {
customerCreated: Customer
}
type Customer @model(table: "customers", pk: "id") {
id: ID!
firstName: String!
lastName: String!
email: String!
}
`
const pubSub = new PubSub()
const resolvers = {
Mutation: {
createCustomer: (root, args, ctx, info) => {
const id = Customer.createOne(args.input).execute()
pubSub.publish('CUSTOMER_CREATED', { id })
return Customer.findById(id).resolveInfo(info).execute()
},
},
Subscription: {
customerCreated: (root, args, ctx, info) => {
subscribe: () => pubsub.asyncIterator(['CUSTOMER_CREATED']),
resolve: () => (root, args, ctx, info) => {
return Customer.findById(root.id).resolveInfo(info).execute()
},
},
},
}

Notice that we only publish the ID of the created record. Many tutorials show publishing the entire object and then omit the resolve function altogether. That would work here too, since our API is very simple. However, by applying the pattern above, we can ensure that the customer object returned by the subscription can be arbitrarily complex (for example, including a number of relationship fields, with those fields including relationship fields, etc.) while still only generating the minimal SQL query necessary.