Skip to content

Commit

Permalink
Remove addToSchema in document transform
Browse files Browse the repository at this point in the history
  • Loading branch information
kazekyo committed Feb 21, 2023
1 parent 64e8376 commit 2a8e14f
Show file tree
Hide file tree
Showing 5 changed files with 19 additions and 131 deletions.
3 changes: 1 addition & 2 deletions .changeset/short-toes-relax.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

Introduce a new feature called DocumentTransform.

DocumentTransform is a functionality that allows you to modify `documents` before they are processed by plugins. You can use functions passed to the `documentTransforms` option to make changes to GraphQL documents or extend the schema, as needed.
DocumentTransform is a functionality that allows you to modify `documents` before they are processed by plugins. You can use functions passed to the `documentTransforms` option to make changes to GraphQL documents.

To use this feature, you can write `documentTransforms` as follows:

Expand All @@ -28,7 +28,6 @@ const config: CodegenConfig = {
// Make some changes to the documents
return documents;
},
addToSchema: 'extend type Query { test: String! }',
},
],
},
Expand Down
109 changes: 14 additions & 95 deletions packages/graphql-codegen-cli/tests/codegen.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1272,118 +1272,37 @@ describe('Codegen Executor', () => {
}
});

it('should be able to extend the schema.', async () => {
const documentTransform: Types.DocumentTransformObject = {
transform: ({ documents }) => {
return documents;
},
addToSchema: `extend type Query { test: String! }`,
};

const output = await executeCodegen({
schema: SIMPLE_TEST_SCHEMA,
documents: `query foo { f }`,
generates: {
'out1.ts': {
plugins: ['typescript', 'typescript-operations'],
documentTransforms: [documentTransform],
},
},
});

expect(output.length).toBe(1);
expect(output[0].content).toContain(`test: Scalars['String']`);
});
});

it('should be able to dynamically extend the schema.', async () => {
const documentTransform: Types.DocumentTransformObject = {
transform: ({ documents }) => {
it('Should transform documents with client-preset', async () => {
const transform: Types.DocumentTransformFunction = ({ documents }) => {
const newDocuments = [
{
document: {
...documents[0].document,
definitions: [
{
...documents[0].document.definitions[0],
selectionSet: {
kind: Kind.SELECTION_SET,
selections: [
{
kind: Kind.FIELD,
name: { kind: Kind.NAME, value: 'test' },
},
],
},
name: { kind: Kind.NAME, value: 'bar' },
} as OperationDefinitionNode,
],
},
},
];
return newDocuments;
},
addToSchema: ({ schema, schemaAst, documents }) => {
// Check that the arguments schema, schemaAST, and documents exist correctly.
// These following are only needed as a test and is of no importance for the extension of the schema in this case.
const fieldObjectTypeFromSchema = schema.definitions.find(
node => node.kind === Kind.OBJECT_TYPE_DEFINITION && node.fields.find(field => field.name.value === 'f')
);
const fieldFromSchemaAST = schemaAst.getQueryType().getFields()['f'];
const operationDefinitionNode = documents[0].document!.definitions[0] as OperationDefinitionNode;

if (operationDefinitionNode.name.value === 'foo' && fieldObjectTypeFromSchema && fieldFromSchemaAST) {
return `extend type Query { test: String! }`;
}
return '';
},
};

const output = await executeCodegen({
schema: SIMPLE_TEST_SCHEMA,
documents: `query foo { f }`,
generates: {
'out1.ts': {
plugins: ['typescript', 'typescript-operations'],
documentTransforms: [documentTransform],
},
},
});

expect(output.length).toBe(1);
expect(output[0].content).toContain(`test: Scalars['String']`);
expect(output[0].content).toContain(`export type FooQuery = { __typename?: 'Query', test: string }`);
});
};

it('Should transform documents with client-preset', async () => {
const transform: Types.DocumentTransformFunction = ({ documents }) => {
const newDocuments = [
{
document: {
...documents[0].document,
definitions: [
{
...documents[0].document.definitions[0],
name: { kind: Kind.NAME, value: 'bar' },
} as OperationDefinitionNode,
],
const output = await executeCodegen({
schema: SIMPLE_TEST_SCHEMA,
documents: `query foo { f }`,
generates: {
'./src/gql/': {
preset: 'client',
documentTransforms: [{ transform }],
},
},
];
return newDocuments;
};
});

const output = await executeCodegen({
schema: SIMPLE_TEST_SCHEMA,
documents: `query foo { f }`,
generates: {
'./src/gql/': {
preset: 'client',
documentTransforms: [{ transform }],
},
},
const fileOutput = output.find(file => file.filename === './src/gql/graphql.ts');
expect(fileOutput.content).toContain('export type BarQuery');
});

const fileOutput = output.find(file => file.filename === './src/gql/graphql.ts');
expect(fileOutput.content).toContain('export type BarQuery');
});
});
22 changes: 1 addition & 21 deletions packages/graphql-codegen-core/src/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,27 +44,6 @@ export async function codegen(options: Types.GenerateOptions): Promise<string> {
}
}

const documentTransforms = Array.isArray(options.documentTransforms) ? options.documentTransforms : [];
for (const documentTransform of documentTransforms) {
const addToSchema = documentTransform.transformObject.addToSchema;
const partialSchema =
typeof addToSchema === 'function'
? addToSchema({
schema: options.schema,
schemaAst: options.schemaAst,
documents: options.documents,
config: {
...options.config,
...documentTransform.config,
},
pluginContext: options.pluginContext,
})
: addToSchema;
if (partialSchema) {
additionalTypeDefs.push(partialSchema);
}
}

const federationInConfig: boolean = pickFlag('federation', options.config);
const isFederation = prioritize(federationInConfig, false);

Expand Down Expand Up @@ -93,6 +72,7 @@ export async function codegen(options: Types.GenerateOptions): Promise<string> {
const schemaDocumentNode =
mergeNeeded || !options.schema ? getCachedDocumentNodeFromSchema(schemaInstance) : options.schema;

const documentTransforms = Array.isArray(options.documentTransforms) ? options.documentTransforms : [];
const transformedDocuments = await transformDocuments({
...options,
documentTransforms,
Expand Down
9 changes: 0 additions & 9 deletions packages/utils/plugins-helpers/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -624,17 +624,8 @@ export namespace Types {
pluginContext?: { [key: string]: any };
}) => Types.Promisable<Types.DocumentFile[]>;

export type DocumentTransformAddToSchemaFunction<Config = object> = (options: {
documents: Types.DocumentFile[];
schema: DocumentNode;
schemaAst?: GraphQLSchema;
config: Config;
pluginContext?: { [key: string]: any };
}) => AddToSchemaResult;

export type DocumentTransformObject<T = object> = {
transform: DocumentTransformFunction<T>;
addToSchema?: AddToSchemaResult | DocumentTransformAddToSchemaFunction;
};

export type DocumentTransformFileName = string;
Expand Down
7 changes: 3 additions & 4 deletions website/src/pages/docs/advanced/document-transform.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { Callout } from '@theguild/components'
# Document Transform

Document transform is a feature that allows you to modify `documents` before they are used by plugins.
You can use functions passed to the `documentTransforms` option to make changes to GraphQL `documents` or extend the schema, as needed.
You can use functions passed to the `documentTransforms` option to make changes to GraphQL `documents`.

## Basic Usage

Document transform has `transform` function and optional `addToSchema` function.
Document transform has `transform` function.

Let's specify an object containing those functions as the `documentTransforms` option as follows:

Expand All @@ -25,8 +25,7 @@ const config: CodegenConfig = {
transform: ({ documents }) => {
// Make some changes to the documents
return documents
},
addToSchema: 'extend type Query { test: String! }'
}
}
]
}
Expand Down

0 comments on commit 2a8e14f

Please sign in to comment.