From 35956ce32cdf45334ee6aa55c698faca71b1093c Mon Sep 17 00:00:00 2001 From: Samuel Andert Date: Wed, 23 Aug 2023 12:44:05 +0200 Subject: [PATCH] dynamically pulling and passing subscriptions from directus to mesh --- .meshrc.yml | 2 +- ...{projects.js => directus_subscriptions.js} | 23 ++++++++++++------- 2 files changed, 16 insertions(+), 9 deletions(-) rename resolvers/{projects.js => directus_subscriptions.js} (82%) diff --git a/.meshrc.yml b/.meshrc.yml index 24175e6..a90438b 100644 --- a/.meshrc.yml +++ b/.meshrc.yml @@ -10,7 +10,7 @@ sources: operationHeaders: Authorization: Bearer {env.DIRECTUS_API} additionalResolvers: - - ./resolvers/projects.js + - ./resolvers/directus_subscriptions.js # - name: Cloudron # handler: diff --git a/resolvers/projects.js b/resolvers/directus_subscriptions.js similarity index 82% rename from resolvers/projects.js rename to resolvers/directus_subscriptions.js index 0223deb..09d752c 100644 --- a/resolvers/projects.js +++ b/resolvers/directus_subscriptions.js @@ -5,13 +5,13 @@ const { parse } = 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); + // Function to find a type definition by name const findTypeDefinition = (typeName) => { return document.definitions.find( @@ -36,9 +36,6 @@ const extractFields = (type, depth = 0) => { .join('\n'); }; -const projectsType = findTypeDefinition('projects'); -const projectsFields = extractFields(projectsType); - const client = createClient({ url: 'wss://directus.andert.me/graphql', keepAlive: 30000, @@ -95,9 +92,19 @@ const handleSubscription = (typeName) => { }; }; +// Find the Subscription type definition +const subscriptionType = findTypeDefinition('Subscription'); + +// Extract the subscription type names, excluding the ones starting with 'directus_' +const subscriptionTypeNames = subscriptionType.fields + .map(field => field.name.value.replace('_mutated', '')) + .filter(name => !name.startsWith('directus_')); + +// Generate subscriptions for each type +const subscriptions = subscriptionTypeNames.reduce((acc, typeName) => { + return { ...acc, ...handleSubscription(typeName) }; +}, {}); + module.exports = { - Subscription: { - ...handleSubscription('projects'), - ...handleSubscription('todos'), - }, + Subscription: subscriptions, }; \ No newline at end of file