Skip to content

Commit

Permalink
Add postTransform option to allow apply custom transformations after …
Browse files Browse the repository at this point in the history
…schema mapping

Signed-off-by: Dmitriy Lazarev <[email protected]>
  • Loading branch information
wKich committed Feb 22, 2024
1 parent 871511d commit d35d38a
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/clean-badgers-tie.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@frontside/hydraphql": patch
---

Add postTransform option to allow apply custom transformations after schema mapping
17 changes: 14 additions & 3 deletions src/transformSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,17 @@ export function transformSchema(
additionalModules: (GraphQLModule | Module)[] = [],
{ generateOpaqueTypes }: { generateOpaqueTypes?: boolean } = {},
) {
const postTransformers: GraphQLModule["postTransform"][] = [];
const modules = [CoreSync(), ...additionalModules];
const directiveMappers: Record<string, FieldDirectiveMapper> = {};
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;
Expand All @@ -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;
}
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
GraphQLFieldConfig,
GraphQLNamedType,
GraphQLObjectType,
GraphQLSchema,
} from "graphql";
import type { Application, Module } from "graphql-modules";

Expand Down Expand Up @@ -64,5 +65,6 @@ export interface NamedType {

export interface GraphQLModule {
mappers?: Record<string, FieldDirectiveMapper>;
postTransform?: (schema: GraphQLSchema) => GraphQLSchema;
module: Module;
}

0 comments on commit d35d38a

Please sign in to comment.