From b9ee596d564d2720b03cdd7eed30f9b31b32e08f Mon Sep 17 00:00:00 2001 From: Samuel Andert Date: Wed, 23 Aug 2023 12:37:30 +0200 Subject: [PATCH] added generic subscribing to directus wss by name --- resolvers/projects.js | 48 ++++++++++++++++++++++++++----------------- 1 file changed, 29 insertions(+), 19 deletions(-) diff --git a/resolvers/projects.js b/resolvers/projects.js index a0cfab5..0223deb 100644 --- a/resolvers/projects.js +++ b/resolvers/projects.js @@ -65,29 +65,39 @@ const generateSubscriptionQuery = (typeName) => { `; }; -// Generate subscription query for 'projects' -const projectsQuery = generateSubscriptionQuery('projects'); -// const todosQuery = generateSubscriptionQuery('todos'); +const handleSubscription = (typeName) => { + const MUTATED = `${typeName.toUpperCase()}_MUTATED`; -client.subscribe( - { - query: projectsQuery, - }, - { - next: data => { - if (data && data.data && data.data.projects_mutated) { - pubsub.publish(PROJECTS_MUTATED, { projects_mutated: data.data.projects_mutated }); - } + const type = findTypeDefinition(typeName); + const fields = extractFields(type); + + const query = generateSubscriptionQuery(typeName); + + client.subscribe( + { + query: query, }, - error: error => console.error('error:', error), - } -); + { + next: data => { + if (data && data.data && data.data[`${typeName}_mutated`]) { + pubsub.publish(MUTATED, { [`${typeName}_mutated`]: data.data[`${typeName}_mutated`] }); + } + }, + error: error => console.error('error:', error), + } + ); + + return { + [`${typeName}_mutated`]: { + subscribe: () => pubsub.asyncIterator([MUTATED]), + resolve: payload => payload[`${typeName}_mutated`], + }, + }; +}; module.exports = { Subscription: { - projects_mutated: { - subscribe: () => pubsub.asyncIterator([PROJECTS_MUTATED]), - resolve: payload => payload.projects_mutated, - }, + ...handleSubscription('projects'), + ...handleSubscription('todos'), }, }; \ No newline at end of file