|
7 | 7 | "@graphql-codegen/graphql-modules-preset": minor
|
8 | 8 | ---
|
9 | 9 |
|
10 |
| -Add a feature to transform documents |
| 10 | +Add a feature to transform documents. |
| 11 | + |
| 12 | +Plugin will have the following functions: |
| 13 | +```my-plugin.js |
| 14 | +module.exports = { |
| 15 | + plugin: () => { |
| 16 | + return 'hello' |
| 17 | + }, |
| 18 | + transformDocuments: (_schema, documents) => { |
| 19 | + // Make some changes to the documents |
| 20 | + return documents; |
| 21 | + }, |
| 22 | + validateBeforeTransformDocuments: () => { |
| 23 | + // Raises an error if necessary |
| 24 | + }, |
| 25 | +}; |
| 26 | +``` |
| 27 | + |
| 28 | +Use it as follows: |
| 29 | + |
| 30 | +```ts |
| 31 | +import type { CodegenConfig } from '@graphql-codegen/cli' |
| 32 | + |
| 33 | +const config: CodegenConfig = { |
| 34 | + schema: 'https://localhost:4000/graphql', |
| 35 | + documents: ['src/**/*.tsx'], |
| 36 | + generates: { |
| 37 | + './src/gql/': { |
| 38 | + preset: 'client', |
| 39 | + documentTransformPlugins: ['./my-plugin.js'], |
| 40 | + plugins: ['./my-plugin.js'] |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | +export default config |
| 45 | +``` |
| 46 | + |
| 47 | +For example, to remove a `@localOnlyDirective` directive from documents: |
| 48 | + |
| 49 | +```my-plugin.js |
| 50 | +const { visit, print } = require('graphql') |
| 51 | + |
| 52 | +module.exports = { |
| 53 | + plugin(schema, documents, config) { |
| 54 | + // Output `documents` as an example. |
| 55 | + return documents.map(documentFile => `${print(documentFile.document)}`).join('\n') |
| 56 | + }, |
| 57 | + transformDocuments(schema, documents, config) { |
| 58 | + return documents.map(documentFile => { |
| 59 | + documentFile.document = visit(documentFile.document, { |
| 60 | + Directive: { |
| 61 | + leave(node) { |
| 62 | + if (node.name.value === 'localOnlyDirective') return null |
| 63 | + } |
| 64 | + } |
| 65 | + }) |
| 66 | + return documentFile |
| 67 | + }) |
| 68 | + } |
| 69 | +} |
| 70 | +``` |
0 commit comments