67
loading...
This website collects cookies to deliver better user experience
This article was published on 2020-12-15 by Jean-Yves Couët @ The Guild Blog
Queries
and Mutations
ready to use!mutation
:mutation addUser {
insert_users(objects: { name: "jyc" }) {
affected_rows
returning {
name
}
}
}
Let's Pimp this graphQL!
graphql-mesh
, it's dead easy! 🚀🚀🚀mkdir newRepo
cd newRepo
yarn init
graphql-mesh
packages
yarn add @graphql-mesh/cli @graphql-mesh/graphql @graphql-mesh/transform-resolvers-composition graphql
.meshrc.yaml
file in the root folder with
sources:
- name: spacexGQL
handler:
graphql:
endpoint: https://api.spacex.land/graphql/
additionalTypeDefs: |
extend type Subscription {
usersAdded: [users]
}
transforms:
- resolversComposition:
- resolver: 'Mutation.insert_users'
composer: ./src/composition/insert_user
additionalResolvers:
- type: Subscription
field: usersAdded
pubsubTopic: usersAdded
Subscription
to listen to user added usersMutation.insert_users
./src/composition/insert_user.js
file with all the logic for this new mutation composition.
module.exports = (next) => async (root, args, context, info) => {
// add returning.id to the selection
info.operation.selectionSet.selections[0].selectionSet.selections.push({
kind: 'Field',
name: {
kind: 'Name',
value: 'returning'
},
arguments: [],
directives: [],
selectionSet: {
kind: 'SelectionSet',
selections: [
{
kind: 'Field',
name: {
kind: 'Name',
value: 'id'
},
arguments: [],
directives: []
}
]
}
})
// send the mutation to the graphQL source
const result = await next(root, args, context, info)
// select returned ids
const ids = result.returning.map((c) => c.id)
// Query users enforcing fields to return
const responseUser = await context.spacexGQL.apiQuery.users(
{
where: { id: { _in: ids } }
},
{
fields: {
id: true,
name: true,
rocket: true,
timestamp: true,
twitter: true
}
}
)
// publish new users
context.pubsub.publish('usersAdded', responseUser)
return result
}
Extending an endpoint with subscription is easy! Thx to tooling.
You can find the source on github.
You see all this in action directly in the playground
67