Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add postTransform option to allow apply custom transformations after schema mapping #20

Merged
merged 1 commit into from
Feb 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
Loading