From 4e7844770cf5254ed49c30798b3d7b23977f7598 Mon Sep 17 00:00:00 2001 From: Samuel Andert Date: Wed, 23 Aug 2023 11:27:51 +0200 Subject: [PATCH] added dynamic mapping ob subscription fields --- resolvers/projects.js | 68 +++++++++++++++++++++++++++++++------------ 1 file changed, 50 insertions(+), 18 deletions(-) diff --git a/resolvers/projects.js b/resolvers/projects.js index 33ac7dc..8372228 100644 --- a/resolvers/projects.js +++ b/resolvers/projects.js @@ -1,10 +1,45 @@ const { createClient } = require('graphql-ws'); const WebSocket = require('ws'); const { PubSub } = require('graphql-subscriptions'); +const { parse, print } = require('graphql'); +const fs = require('fs'); const pubsub = new PubSub(); const PROJECTS_MUTATED = 'PROJECTS_MUTATED'; +// Read the schema file +const schema = fs.readFileSync('./schemas/directus.graphql', 'utf8'); + +// Parse the schema +const document = parse(schema); + +// Find the projects type definition +const projectsType = document.definitions.find( + def => def.kind === 'ObjectTypeDefinition' && def.name.value === 'projects' +); + +// Find the directus_users type definition +const directusUsersType = document.definitions.find( + def => def.kind === 'ObjectTypeDefinition' && def.name.value === 'directus_users' +); + +// Extract the fields excluding the ones ending with '_func', of object type, and specific fields +const extractFields = (type) => { + const fields = type.fields + .filter(field => !field.name.value.endsWith('_func') && field.type.kind === 'NamedType' && !['avatar', 'role'].includes(field.name.value)) + .map(field => field.name.value); + + // Check if 'id' field exists in the type + if (type.fields.some(field => field.name.value === 'id')) { + fields.unshift('id'); // Add 'id' at the start of the fields array + } + + return fields.join('\n'); +}; + +const projectsFields = extractFields(projectsType); +const directusUsersFields = extractFields(directusUsersType); + const client = createClient({ url: 'wss://directus.andert.me/graphql', keepAlive: 30000, @@ -14,26 +49,23 @@ const client = createClient({ }, }); +const finalQuery = ` + subscription { + projects_mutated { + key + event + data { + ${projectsFields.replace('user_created', `user_created { ${directusUsersFields} }`).replace('user_updated', `user_updated { ${directusUsersFields} }`)} + } + } + } +`; + +console.log(finalQuery); + client.subscribe( { - query: ` - subscription { - projects_mutated { - key - event - data { - id - text - date_updated - user_updated { - first_name - last_name - email - } - } - } - } - `, + query: finalQuery, }, { next: data => {