From 167382459daaff7d33e313b5a54e293219148c58 Mon Sep 17 00:00:00 2001 From: Jay Cammarano <67079013+jaycammarano@users.noreply.github.com> Date: Sat, 14 Aug 2021 15:13:53 -0400 Subject: [PATCH] Alias Support Within GraphQL (#7410) * graphQL support for aliases * moved aliases to its own function parseAliases * Tweak types Co-authored-by: rijkvanzanten --- api/src/services/graphql.ts | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/api/src/services/graphql.ts b/api/src/services/graphql.ts index de98642255..766eb3a40f 100644 --- a/api/src/services/graphql.ts +++ b/api/src/services/graphql.ts @@ -966,7 +966,6 @@ export class GraphQLService { const selections = this.replaceFragmentsInSelections(info.fieldNodes[0]?.selectionSet?.selections, info.fragments); if (!selections) return null; - const args: Record = this.parseArgs(info.fieldNodes[0].arguments || [], info.variableValues); let query: Record; @@ -1001,6 +1000,7 @@ export class GraphQLService { if (args.id) { return result?.[0] || null; } + if (query.group) { // for every entry in result add a group field based on query.group; result.map((field) => { @@ -1167,9 +1167,22 @@ export class GraphQLService { ): Query { const query: Query = sanitizeQuery(rawQuery, this.accountability); + const parseAliases = (selections: readonly SelectionNode[]) => { + const aliases: Record = {}; + + for (const selection of selections) { + if (selection.kind !== 'Field') continue; + + if (selection.alias?.value) { + aliases[selection.alias.value] = selection.name.value; + } + } + + return aliases; + }; + const parseFields = (selections: readonly SelectionNode[], parent?: string): string[] => { const fields: string[] = []; - for (let selection of selections) { if ((selection.kind === 'Field' || selection.kind === 'InlineFragment') !== true) continue; selection = selection as FieldNode | InlineFragmentNode; @@ -1183,7 +1196,8 @@ export class GraphQLService { } else { // filter out graphql pointers, like __typename if (selection.name.value.startsWith('__')) continue; - current = selection.name.value; + + current = selection.alias?.value ?? selection.name.value; if (parent) { current = `${parent}.${current}`; @@ -1217,7 +1231,12 @@ export class GraphQLService { } return uniq(fields); }; + + query.alias = parseAliases(selections); query.fields = parseFields(selections); + + validateQuery(query); + return query; } @@ -1248,11 +1267,8 @@ export class GraphQLService { validateQuery(query); - validateQuery(query); - return query; } - /** * Convert Directus-Exception into a GraphQL format, so it can be returned by GraphQL properly. */