I just came across this entry and implemented a solution for graphql-codegen and would like to leave it here.
Solution based on https://github.com/nestjs/graphql/issues/679 and is transformed into typescript.
Create a file named "operationsFromSchema.ts" with following content:
import {
buildClientSchema,
DocumentNode,
getIntrospectionQuery,
GraphQLSchema,
OperationTypeNode,
parse,
print,
} from 'graphql';
import { buildOperationNodeForField } from '@graphql-tools/utils';
/**
* @description Method to get schema from URL.
* @param {string} url
* @return {Promise<GraphQLSchema>}
*/
async function getSchemaFromUrl(url: string): Promise<GraphQLSchema> {
// eslint-disable-next-line no-useless-catch
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: getIntrospectionQuery().toString(),
}),
});
const { data } = await response.json();
return buildClientSchema(data);
} catch (e) {
throw e;
}
}
/**
* @description Get operations from schema.
* See: https://github.com/nestjs/graphql/issues/679
* @param {string} url
* @return {Promise<DocumentNode>}
*/
async function operationsFromSchema(url: string): Promise<DocumentNode> {
const schema: GraphQLSchema = await getSchemaFromUrl(url);
const operationsDictionary = {
query: { ...(schema.getQueryType()?.getFields() || {}) },
mutation: { ...(schema.getMutationType()?.getFields() || {}) },
subscription: { ...(schema.getSubscriptionType()?.getFields() || {}) },
};
let documentString: string = '';
Object.keys(operationsDictionary).forEach((kind: string) => {
Object.keys((operationsDictionary as any)[kind]).forEach((field: string) => {
const operationAST = buildOperationNodeForField({
schema,
kind: kind as OperationTypeNode,
field,
});
documentString += print(operationAST);
});
});
return parse(documentString);
}
export default operationsFromSchema;
After the file has been created we can use these lines of code as a loader in the codegen file.
import { CodegenConfig } from '@graphql-codegen/cli'
const config: CodegenConfig = {
schema: process.env.REACT_APP_ADMIN_API_URL,
overwrite: true,
generates: {
'./src/graphql/schema.tsx': {
documents: {
[process.env.REACT_APP_ADMIN_API_URL]: {
loader: './src/graphql/operationsFromSchema.ts',
}
},
plugins: [
'typescript',
'typescript-operations',
'typescript-react-apollo'
],
config: {
dedupeOperationSuffix: true,
omitOperationSuffix: true,
},
},
}
}
export default config