{"size": 1525, "ext": "js", "max_stars_repo_path": "examples/subscription/mqemitter-mongodb-subscription.js", "max_stars_repo_name": "FdezRomero/mercurius", "max_stars_repo_stars_event_min_datetime": "2020-09-25T13:17:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:20:21.000Z", "max_issues_repo_path": "examples/subscription/mqemitter-mongodb-subscription.js", "max_issues_repo_name": "FdezRomero/mercurius", "max_issues_repo_issues_event_min_datetime": "2020-09-25T09:29:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T17:21:28.000Z", "max_forks_repo_path": "examples/subscription/mqemitter-mongodb-subscription.js", "max_forks_repo_name": "FdezRomero/mercurius", "max_forks_repo_forks_event_min_datetime": "2020-09-25T19:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T20:03:28.000Z"}
{"max_stars_count": 1177, "max_issues_count": 307, "max_forks_count": 148, "avg_line_length": 16.7582417582, "max_line_length": 67, "alphanum_fraction": 0.5836065574}
'use strict'

const mercurius = require('mercurius')
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(mercurius, {
      schema,
      resolvers,
      subscription: {
        emitter,
        handle
      }
    })

    // start server
    await app.listen(3000)
  } catch (error) {
    app.log.error(error)
  }
}

start()
