Skip to content

Commit

Permalink
add mqemitter mongodb subscription example (#81) (#250)
Browse files Browse the repository at this point in the history
  • Loading branch information
santiagoalmeidabolannos authored Aug 15, 2020
1 parent 0e7aa52 commit 0c1f6ef
Showing 1 changed file with 90 additions and 0 deletions.
90 changes: 90 additions & 0 deletions examples/subscription/mqemitter-mongodb-subscription.js
Original file line number Diff line number Diff line change
@@ -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()

0 comments on commit 0c1f6ef

Please sign in to comment.