Using GraphCool for my GraphQL backend, I would like to know how to subscribe to only a single item given the ID. I've been looking at the docs and trying to use filters, but I still can't figure it out. If I wanted to subscribe to all item mutations, I understand that I'd have to do it like so:
subscription {
Photo{
node {
id
title
url
}
}
}
How do I listen to an item with a given ID?
The filter capabilities known from the Simple API can be used in the Subscription API as well. You can use the node
property inside the filter
object for this. Here's some example for subscription filters in action:
Using mutation_in
, we can decide whether we want to listen to created, updated or deleted events (or a mix of them):
subscription {
Photo(filter: {
mutation_in: [CREATED]
}) {
node {
id
title
url
}
}
}
When listening for updates, we can further specify to only listen to updates for specific fields using updatedFields_contains
, updatedFields_contains_every
and updatedFields_contains_some
:
subscription {
# we can only use `updatedFields_x` filters together with `UPATED`
# so we use OR
Photo(filter: {
OR: [{
mutation_in: [UPDATED]
updatedFields_contains: "title"
}, {
mutation_in: [CREATED]
}]
}) {
previousValues {
title # contains old title
}
node {
id
title # contains new title
url
}
}
}
For all subscription queries, we can further refine the subscription conditions by using node
. This is the same filter used for allPhoto
, for example:
subscription updatedPhoto($id: ID!) {
Photo(filter: {
mutation_in: [UPDATED]
node: {
id: $id
}
}) {
previousValues {
title # contains old title
}
node {
id
title # contains new title
url
}
}
}