abstracing more generic resolving of subsciptions schema to querydata mapping

This commit is contained in:
Samuel Andert 2023-08-23 11:52:27 +02:00
parent 4e7844770c
commit 019593a4a1

View File

@ -1,7 +1,7 @@
const { createClient } = require('graphql-ws');
const WebSocket = require('ws');
const { PubSub } = require('graphql-subscriptions');
const { parse, print } = require('graphql');
const { parse } = require('graphql');
const fs = require('fs');
const pubsub = new PubSub();
@ -12,33 +12,32 @@ 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');
// Function to find a type definition by name
const findTypeDefinition = (typeName) => {
return document.definitions.find(
def => def.kind === 'ObjectTypeDefinition' && def.name.value === typeName
);
};
// Extract the fields excluding the ones ending with '_func', of object type, and specific fields
const extractFields = (type, depth = 0) => {
return type.fields
.filter(field => !field.name.value.endsWith('_func') && !['avatar', 'role'].includes(field.name.value))
.map(field => {
if (field.type.kind === 'NamedType' && depth < 1) {
// If the field is of object type and we are not too deep, recursively extract its fields
const nestedType = findTypeDefinition(field.type.name.value);
if (nestedType) {
return `${field.name.value} {\n${extractFields(nestedType, depth + 1)}\n}`;
}
}
return field.name.value;
})
.join('\n');
};
const projectsType = findTypeDefinition('projects');
const projectsFields = extractFields(projectsType);
const directusUsersFields = extractFields(directusUsersType);
const client = createClient({
url: 'wss://directus.andert.me/graphql',
@ -55,7 +54,7 @@ const finalQuery = `
key
event
data {
${projectsFields.replace('user_created', `user_created { ${directusUsersFields} }`).replace('user_updated', `user_updated { ${directusUsersFields} }`)}
${projectsFields}
}
}
}