diff --git a/examples/subscription/memory.js b/examples/subscription/memory.js new file mode 100644 index 00000000..754e543c --- /dev/null +++ b/examples/subscription/memory.js @@ -0,0 +1,84 @@ +'use strict' + +const mercurius = require('../..') +const Fastify = require('fastify') + +const app = Fastify({ logger: { level: 'debug' } }) + +// 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') + } + } + } +} + +// server start +const start = async () => { + try { + // register GraphQl + app.register(mercurius, { + schema, + resolvers, + graphiql: true, + subscription: { + async onConnect ({ payload }) { + app.log.info({ payload }, 'connection_init data') + return true + } + } + }) + + // start server + await app.listen({ port: 3000 }) + } catch (error) { + app.log.error(error) + } +} + +start() diff --git a/static/main.js b/static/main.js index 485d39e8..080ee29e 100644 --- a/static/main.js +++ b/static/main.js @@ -42,7 +42,7 @@ function render () { function importDependencies () { const link = document.createElement('link') - link.href = 'https://unpkg.com/graphiql@2.0.2/graphiql.min.css' + link.href = 'https://unpkg.com/graphiql@2.0.9/graphiql.min.css' link.type = 'text/css' link.rel = 'stylesheet' link.media = 'screen,print' @@ -52,7 +52,7 @@ function importDependencies () { return importer.urls([ 'https://unpkg.com/react@18.2.0/umd/react.production.min.js', 'https://unpkg.com/react-dom@18.2.0/umd/react-dom.production.min.js', - 'https://unpkg.com/graphiql@2.0.2/graphiql.min.js' + 'https://unpkg.com/graphiql@2.0.9/graphiql.min.js' ]) } diff --git a/static/sw.js b/static/sw.js index 2c9f3ca5..ef32ba49 100644 --- a/static/sw.js +++ b/static/sw.js @@ -2,13 +2,13 @@ self.addEventListener('install', function (e) { e.waitUntil( - caches.open('graphiql-v2.0.2').then(function (cache) { + caches.open('graphiql-v2.0.9').then(function (cache) { return cache.addAll([ './main.js', - 'https://unpkg.com/graphiql@2.0.2/graphiql.css', + 'https://unpkg.com/graphiql@2.0.9/graphiql.css', 'https://unpkg.com/react@18.2.0/umd/react.production.min.js', 'https://unpkg.com/react-dom@18.2.0/umd/react-dom.production.min.js', - 'https://unpkg.com/graphiql@2.0.2/graphiql.min.js' + 'https://unpkg.com/graphiql@2.0.9/graphiql.min.js' ]) }) )