From d35d38ae92c76a1b6c58cf9ebdd90c40da700fe7 Mon Sep 17 00:00:00 2001 From: Dmitriy Lazarev Date: Fri, 23 Feb 2024 00:41:46 +0400 Subject: [PATCH] Add postTransform option to allow apply custom transformations after schema mapping Signed-off-by: Dmitriy Lazarev --- .changeset/clean-badgers-tie.md | 5 +++++ src/transformSchema.ts | 17 ++++++++++++++--- src/types.ts | 2 ++ 3 files changed, 21 insertions(+), 3 deletions(-) create mode 100644 .changeset/clean-badgers-tie.md diff --git a/.changeset/clean-badgers-tie.md b/.changeset/clean-badgers-tie.md new file mode 100644 index 0000000..4ae6dc7 --- /dev/null +++ b/.changeset/clean-badgers-tie.md @@ -0,0 +1,5 @@ +--- +"@frontside/hydraphql": patch +--- + +Add postTransform option to allow apply custom transformations after schema mapping diff --git a/src/transformSchema.ts b/src/transformSchema.ts index 6d4874e..e354e16 100644 --- a/src/transformSchema.ts +++ b/src/transformSchema.ts @@ -11,11 +11,17 @@ export function transformSchema( additionalModules: (GraphQLModule | Module)[] = [], { generateOpaqueTypes }: { generateOpaqueTypes?: boolean } = {}, ) { + const postTransformers: GraphQLModule["postTransform"][] = []; const modules = [CoreSync(), ...additionalModules]; const directiveMappers: Record = {}; const typeDefs: DocumentNode[] = modules.flatMap((m) => { - const { module: gqlModule, mappers = {} } = "id" in m ? { module: m } : m; + const { + module: gqlModule, + mappers = {}, + postTransform = undefined, + } = "id" in m ? { module: m } : m; const documents = gqlModule.typeDefs; + postTransformers.push(postTransform); documents.forEach((document) => { document.definitions.forEach((definition) => { if (definition.kind !== Kind.DIRECTIVE_DEFINITION) return; @@ -36,10 +42,15 @@ export function transformSchema( generateOpaqueTypes, }); - const errors = validateSchema(schema); + const postSchema = postTransformers.reduce( + (s, transform) => transform?.(s) ?? s, + schema, + ); + + const errors = validateSchema(postSchema); if (errors.length > 0) { throw new Error(errors.map((e) => e.message).join("\n")); } - return schema; + return postSchema; } diff --git a/src/types.ts b/src/types.ts index 2a797ad..9c3b120 100644 --- a/src/types.ts +++ b/src/types.ts @@ -4,6 +4,7 @@ import type { GraphQLFieldConfig, GraphQLNamedType, GraphQLObjectType, + GraphQLSchema, } from "graphql"; import type { Application, Module } from "graphql-modules"; @@ -64,5 +65,6 @@ export interface NamedType { export interface GraphQLModule { mappers?: Record; + postTransform?: (schema: GraphQLSchema) => GraphQLSchema; module: Module; }