From 0c1f6ef6f3017565a3386ec40bba999e6703c427 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Santiago=20Almeida=20Bola=C3=B1os?= Date: Sat, 15 Aug 2020 14:18:38 +0300 Subject: [PATCH] add mqemitter mongodb subscription example (#81) (#250) --- .../mqemitter-mongodb-subscription.js | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 examples/subscription/mqemitter-mongodb-subscription.js diff --git a/examples/subscription/mqemitter-mongodb-subscription.js b/examples/subscription/mqemitter-mongodb-subscription.js new file mode 100644 index 00000000..4f182fdc --- /dev/null +++ b/examples/subscription/mqemitter-mongodb-subscription.js @@ -0,0 +1,90 @@ +'use strict' + +const GQL = require('fastify-gql') +const Fastify = require('fastify') +const mongodbMQEmitter = require('mqemitter-mongodb') + +const app = Fastify({ logger: true }) + +// mq +let emitter + +// list of products +const products = [] + +// graphql schema +const schema = ` + type Product { + name: String! + state: String! + } + + type Query { + products: [Product] + } + + type Mutation { + addProduct(name: String!, state: String!): Product + } + + type Subscription { + productAdded: Product + } +` + +// graphql resolvers +const resolvers = { + Query: { + products: () => products + }, + Mutation: { + addProduct: async (_, { name, state }, { pubsub }) => { + const product = { name, state } + + products.push(product) + + pubsub.publish({ + topic: 'new_product_updates', + payload: { + productAdded: product + } + }) + + return product + } + }, + Subscription: { + productAdded: { + subscribe: async (_, __, { pubsub }) => { + return await pubsub.subscribe('new_product_updates') + } + } + } +} + +const handle = (conn) => conn.pipe(conn) + +// server start +const start = async () => { + try { + // initialize emitter + emitter = mongodbMQEmitter({ url: 'mongodb://localhost/test' }) + + // register GraphQl + app.register(GQL, { + schema, + resolvers, + subscription: { + emitter, + handle + } + }) + + // start server + await app.listen(3000) + } catch (error) { + app.log.error(error) + } +} + +start()