Live Queries#
GraphQL Live Query implementation from Laurin Quast can be used in GraphQL Mesh with a few additions in the configuration.
Basic Usage#
You have a Query
root field that returns all Todo
entities from your data source like below.
query getTodos {
todos {
id
content
}
}
And you want to update this operation result automatically without manual refresh when Mutation.addTodo
is called.
You only need to add the following to your existing configuration.
additionalTypeDefs: |
directive @live on QUERY
liveQueryInvalidations:
- field: Mutation.addTodo
invalidate:
- Query.todos
Then you can send a live query with @live
directive.
query getTodos @live {
todos {
id
content
}
}
This will start a real-time connection between the server and your client. The response of todos
will get updated whenever addTodo
is called.
ID Based Invalidation#
Let's say you have the following query that returns a specific Todo
entity based on id
field;
query getTodo($id: ID!) {
todo(id: $id) {
id
content
}
}
If you update this entity with editTodo
mutation field on your backend, then you want to invalidate this entity specifically instead of validating all todo
queries;
liveQueryInvalidations:
- field: Mutation.editTodo
invalidate:
- Todo:{args.id}
In a case where the field resolver resolves null but might resolve to an object type later, e.g., because the visibility got update the field that uses a specific id argument can be invalidated in the following way:
liveQueryInvalidations:
- field: Mutation.editTodo
invalidate:
- Query.todo(id:"{args.id}")
Programmatic Usage#
liveQueryStore
is available in GraphQL Context, so you can access it in resolvers composition functions that wrap existing resolvers or additional resolvers;
transforms:
- resolversComposition:
- resolver: Mutation.editTodo
composer: invalidate-todo#invalidateTodo
And in this code file;
module.exports = {
invalidateTodo: next => async (root, args, context, info) => {
const result = await next(root, args, context, info);
context.liveQueryStore.invalidate(`Todo:${args.id}`);
return result;
}
}
You can learn more about GraphQL Live Query in its documentation.
You can check out our example that uses live queries