-
Notifications
You must be signed in to change notification settings - Fork 240
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
- Loading branch information
1 parent
0e7aa52
commit 0c1f6ef
Showing
1 changed file
with
90 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |