This example demonstrates subscriptions property available to us in prisma.yml that can be used to implement event-driven business logic.
Note:
prismais listed as a development dependency and script in this project'spackage.json. This means you can invoke the Prisma CLI without having it globally installed on your machine (by prefixing it withyarn), e.g.yarn prisma deployoryarn prisma playground. If you have the Prisma CLI installed globally (which you can do withnpm install -g prisma), you can omit theyarnprefix.
Clone the Prisma monorepo and navigate to this directory or download only this example with the following command:
curl https://codeload.github.com/graphcool/prisma/tar.gz/master | tar -xz --strip=2 prisma-master/examples/server-side-subscriptionsNext, navigate into the downloaded folder and install the NPM dependencies:
cd server-side-subscriptions
yarn installYou can now deploy the Prisma service (note that this requires you to have Docker installed on your machine - if that's not the case, follow the collapsed instructions below the code block):
yarn prisma deployI don't have Docker installed on my machine
To deploy your service to a demo server (rather than locally with Docker), please follow this link.
The subscriptions property is used to implement event-based business logic using POST endpoints.
Here is how we have defined the subscription in prisma.yml for this example.
subscriptions:
welcomeNewUser:
query: subscription.graphql
webhook: http://ptsv2.com/t/prisma/postLet us assume that we want to send a welcome email to new user. We will define that subscription as above.
welcomeNewUser is the name of the subscription.
query: subscription.graphql is the file that contains the subscription query. Note that we are listening to the "CREATED" mutation events.
subscription {
user(where: { mutation_in: [CREATED] }) {
mutation
node {
id
name
}
}
}webhook: http://ptsv2.com/t/prisma/post is a mock endpoint consuming this query. On creation of a new User Prisma service will call this endpoint with Post data selected in the subscription query.
The best way to test this subscription logic is to create a user and observe the mock POST endpoint.
You can either start the desktop app via
yarn playgroundOr you can open a Playground by navigating to http://localhost:4466/server-side-subscription in your browser.
mutation M {
createUser(data: { name: "Prisma" }) {
id
name
}
}You will notice a dump of your request on this page of this shape:
{"data":{"user":{"mutation":"CREATED","node":{"id":"cjjk6a0op000w0982jlzt4m55","name":"Prisma"}}}}