From 3e2ee1ee0f83cb77a3f8d8a753b9dfe90f06f90f Mon Sep 17 00:00:00 2001 From: Samuel Andert Date: Wed, 23 Aug 2023 08:53:31 +0200 Subject: [PATCH] fixing subscription resolver --- resolvers/projects.js | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/resolvers/projects.js b/resolvers/projects.js index 6131964..bd8ed94 100644 --- a/resolvers/projects.js +++ b/resolvers/projects.js @@ -1,5 +1,9 @@ const { createClient } = require('graphql-ws'); const WebSocket = require('ws'); +const { PubSub } = require('graphql-subscriptions'); + +const pubsub = new PubSub(); +const PROJECTS_MUTATED = 'PROJECTS_MUTATED'; const client = createClient({ url: 'wss://directus.andert.me/graphql', @@ -8,11 +12,6 @@ const client = createClient({ connectionParams: async () => { return { access_token: 'Mb3NMqKwiyesxDeJRTD72VZZ6f4t3mBr' }; }, - on: { - opened: () => console.log('Connection opened'), - closed: () => console.log('Connection closed'), - error: (error) => console.log('Connection error:', error), - }, }); client.subscribe( @@ -20,22 +19,35 @@ client.subscribe( query: ` subscription { projects_mutated { + key + event data { + id text date_updated user_updated { first_name } } - event - key } } `, }, { - next: data => console.log('data:', data), + next: data => { + if (data && data.data && data.data.projects_mutated) { + pubsub.publish(PROJECTS_MUTATED, { projects_mutated: data.data.projects_mutated }); + } + }, error: error => console.error('error:', error), - complete: () => console.log('complete'), } -); \ No newline at end of file +); + +module.exports = { + Subscription: { + projects_mutated: { + subscribe: () => pubsub.asyncIterator([PROJECTS_MUTATED]), + resolve: payload => payload.projects_mutated, + }, + }, +}; \ No newline at end of file