-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(graphql-codegen-typed-document-nodes): generate typed nodes
- Loading branch information
Showing
9 changed files
with
1,871 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2024 Aleksei Potsetsuev (Wroud) | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
147 changes: 147 additions & 0 deletions
147
packages/graphql-codegen-typed-document-nodes/README.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,147 @@ | ||
# graphql-codegen-typed-document-nodes | ||
|
||
[![ESM-only package][package]][esm-info-url] | ||
[![NPM version][npm]][npm-url] | ||
|
||
<!-- [![Install size][size]][size-url] --> | ||
|
||
[package]: https://img.shields.io/badge/package-ESM--only-ffe536.svg | ||
[esm-info-url]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c | ||
[npm]: https://img.shields.io/npm/v/graphql-codegen-typed-document-nodes.svg | ||
[npm-url]: https://npmjs.com/package/graphql-codegen-typed-document-nodes | ||
[size]: https://packagephobia.com/badge?p=graphql-codegen-typed-document-nodes | ||
[size-url]: https://packagephobia.com/result?p=graphql-codegen-typed-document-nodes | ||
|
||
`graphql-codegen-typed-document-nodes` is a custom plugin for GraphQL Code Generator that generates typed document nodes for TypeScript operations and fragments. It enhances type safety by providing exportable types for GraphQL queries, mutations, and fragments. | ||
|
||
## Features | ||
|
||
- **TypedDocumentNode generation**: Automatically generates typed document nodes for operations and fragments. | ||
- **Type-safe GraphQL operations**: Ensures queries, mutations, and fragments have precise TypeScript types. | ||
- **Seamless integration**: Works as a plugin for GraphQL Code Generator. | ||
- [Pure ESM package][esm-info-url] | ||
|
||
## Installation | ||
|
||
This plugin requires the `@graphql-codegen/typescript-operations` plugin to function correctly. | ||
|
||
Install via npm: | ||
|
||
```sh | ||
npm install -D graphql-codegen-typed-document-nodes @graphql-codegen/typescript-operations | ||
``` | ||
|
||
Install via yarn: | ||
|
||
```sh | ||
yarn add -D graphql-codegen-typed-document-nodes @graphql-codegen/typescript-operations | ||
``` | ||
|
||
## Usage | ||
|
||
This configuration will generate `*.generated.{ts,tsx}` files for each `.ts` or `.tsx` file containing operations or fragments. | ||
Here’s an example configuration using `graphql-codegen-typed-document-nodes` in a `codegen.ts` file: | ||
|
||
```ts | ||
import type { CodegenConfig } from "@graphql-codegen/cli"; | ||
|
||
const config: CodegenConfig = { | ||
pluginLoader: (name) => import(name), | ||
schema: "schema.graphql", | ||
documents: "src/**/*.graphql", | ||
ignoreNoDocuments: true, | ||
generates: { | ||
"./src/generated/common-types.ts": { | ||
plugins: ["typescript"], | ||
config: { | ||
avoidOptionals: true, | ||
}, | ||
}, | ||
".": { | ||
preset: "near-operation-file", | ||
plugins: ["typescript-operations", "typed-document-nodes"], | ||
presetConfig: { | ||
baseTypesPath: "./src/generated/common-types.ts", | ||
}, | ||
config: { | ||
inlineFragmentTypes: "mask", | ||
}, | ||
}, | ||
}, | ||
}; | ||
|
||
export default config; | ||
``` | ||
|
||
### Example Query | ||
|
||
Given the following query: | ||
|
||
```ts | ||
const getUserQuery = gql` | ||
query GetUser($id: ID!) { | ||
user(id: $id) { | ||
id | ||
name | ||
} | ||
} | ||
`; | ||
``` | ||
|
||
This plugin will generate the following type: | ||
|
||
```ts | ||
... | ||
export type GetUserDocument = Types.TypedDocumentNode<GetUserQuery, GetUserQueryVariables>; | ||
``` | ||
|
||
You can now use the generated type in your application: | ||
|
||
```ts | ||
import { GetUserDocument } from "./getUserQuery.generated.ts"; | ||
|
||
const getUserQuery: GetUserDocument = gql` | ||
query GetUser($id: ID!) { | ||
user(id: $id) { | ||
id | ||
name | ||
} | ||
} | ||
`; | ||
``` | ||
|
||
## FAQ | ||
|
||
### **Error: Unable to load template plugin matching 'typed-document-nodes'** | ||
|
||
```text | ||
Unable to load template plugin matching 'typed-document-nodes'. | ||
Reason: | ||
require() of ES Module graphql-codegen-typed-document-nodes/out/index.js fr… | ||
Instead change the require of index.js in .yarn/__virtual__/@graphql-codegen-cli-vir… | ||
``` | ||
|
||
**Solution:** | ||
This error occurs because `@graphql-codegen` expects the plugin to be loaded in a specific way. To resolve this, add a `pluginLoader` function to your GraphQL Code Generator configuration: | ||
|
||
```ts | ||
import type { CodegenConfig } from "@graphql-codegen/cli"; | ||
|
||
const config: CodegenConfig = { | ||
... | ||
pluginLoader: (name) => import(name), | ||
... | ||
}; | ||
|
||
export default config; | ||
``` | ||
|
||
This ensures the plugin is loaded as an ES module, preventing the `require()` error. | ||
|
||
## Changelog | ||
|
||
All notable changes to this project will be documented in the [CHANGELOG](./CHANGELOG.md) file. | ||
|
||
## License | ||
|
||
This project is licensed under the MIT License. See the [LICENSE](./LICENSE) file for details. |
82 changes: 82 additions & 0 deletions
82
packages/graphql-codegen-typed-document-nodes/package.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
{ | ||
"name": "graphql-codegen-typed-document-nodes", | ||
"description": "A custom GraphQL Code Generator plugin to generate typed document nodes for TypeScript operations and fragments. Provides enhanced type safety with generated exports for GraphQL queries, mutations, and fragments.", | ||
"version": "0.0.0", | ||
"type": "module", | ||
"packageManager": "[email protected]", | ||
"license": "MIT", | ||
"author": "Wroud", | ||
"homepage": "https://wroud.dev/", | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/Wroud/foundation", | ||
"directory": "packages/graphql-codegen-typed-document-nodes" | ||
}, | ||
"sideEffects": [], | ||
"module": "./lib/index.js", | ||
"exports": { | ||
".": "./lib/index.js", | ||
"./*": "./lib/*.js" | ||
}, | ||
"files": [ | ||
"package.json", | ||
"LICENSE", | ||
"README.md", | ||
"CHANGELOG.md", | ||
"lib", | ||
"!lib/**/*.d.ts.map", | ||
"!lib/**/*.test.js", | ||
"!lib/**/*.test.d.ts", | ||
"!lib/**/*.test.d.ts.map", | ||
"!lib/**/*.test.js.map", | ||
"!lib/tests", | ||
"!.tsbuildinfo" | ||
], | ||
"scripts": { | ||
"ci:release": "yarn ci release --prefix gql-codegen-doc-nodes-v", | ||
"ci:git-tag": "yarn ci git-tag --prefix gql-codegen-doc-nodes-v", | ||
"ci:release-github": "yarn ci release-github --prefix gql-codegen-doc-nodes-v", | ||
"test": "tests-runner", | ||
"test:ci": "CI=true yarn run test", | ||
"build": "tsc -b", | ||
"watch:tsc": "tsc -b -w", | ||
"dev": "concurrently \"npm:watch:*\"", | ||
"clear": "rimraf ./lib" | ||
}, | ||
"dependencies": { | ||
"@graphql-codegen/plugin-helpers": "^5", | ||
"@graphql-codegen/visitor-plugin-common": "^5", | ||
"change-case-all": "^2", | ||
"graphql": "^16" | ||
}, | ||
"devDependencies": { | ||
"@types/node": "^20", | ||
"@vitest/coverage-v8": "^2", | ||
"@wroud/ci": "workspace:*", | ||
"@wroud/tests-runner": "workspace:*", | ||
"@wroud/tsconfig": "workspace:*", | ||
"concurrently": "^8", | ||
"rimraf": "^6", | ||
"tslib": "^2", | ||
"typescript": "^5", | ||
"vitest": "^2" | ||
}, | ||
"peerDependencies": { | ||
"@graphql-codegen/typescript-operations": "*" | ||
}, | ||
"keywords": [ | ||
"graphql", | ||
"codegen", | ||
"plugin", | ||
"typescript", | ||
"graphql-codegen", | ||
"typed-document-node", | ||
"graphql-fragments", | ||
"graphql-operations", | ||
"graphql-mutations", | ||
"graphql-queries", | ||
"typescript-documents", | ||
"type-safe", | ||
"graphql-tools" | ||
] | ||
} |
65 changes: 65 additions & 0 deletions
65
packages/graphql-codegen-typed-document-nodes/src/index.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
import { | ||
type PluginFunction, | ||
type Types, | ||
} from "@graphql-codegen/plugin-helpers"; | ||
import { | ||
concatAST, | ||
type DefinitionNode, | ||
GraphQLSchema, | ||
Kind, | ||
type OperationDefinitionNode, | ||
} from "graphql"; | ||
import { TypeScriptDocumentsVisitor } from "./visitor.js"; | ||
import type { RawDocumentsConfig } from "@graphql-codegen/visitor-plugin-common"; | ||
|
||
export const plugin: PluginFunction< | ||
RawDocumentsConfig, | ||
Types.ComplexPluginOutput | ||
> = ( | ||
schema: GraphQLSchema, | ||
rawDocuments: Types.DocumentFile[], | ||
config: RawDocumentsConfig, | ||
) => { | ||
const allAst = concatAST(rawDocuments.map((doc) => doc.document!)); | ||
|
||
const visitor = new TypeScriptDocumentsVisitor(schema, config); | ||
|
||
const exportConsts = generateExportTypes(allAst.definitions, visitor); | ||
const content = [...exportConsts].join("\n"); | ||
|
||
return { | ||
content, | ||
}; | ||
}; | ||
|
||
/** | ||
* Generates export type definitions for operations and fragments. | ||
*/ | ||
function generateExportTypes( | ||
definitions: readonly DefinitionNode[], | ||
visitor: TypeScriptDocumentsVisitor, | ||
): string[] { | ||
const exportTypes: string[] = []; | ||
|
||
for (const def of definitions) { | ||
if (def.kind === Kind.OPERATION_DEFINITION) { | ||
const operationNode = def as OperationDefinitionNode; | ||
const operationName = visitor.getOperationName(operationNode); | ||
const resultType = visitor.getOperationResultType(operationNode); | ||
const variablesType = visitor.convertName(resultType, { | ||
suffix: "Variables", | ||
}); | ||
|
||
exportTypes.push( | ||
`export type ${operationName}Document = Types.TypedDocumentNode<${resultType}, ${variablesType}>;`, | ||
); | ||
} else if (def.kind === Kind.FRAGMENT_DEFINITION) { | ||
const fragmentName = visitor.getFragmentName(def); | ||
exportTypes.push( | ||
`export type ${fragmentName}Doc = Types.TypedDocumentNode<${fragmentName}, unknown>;`, | ||
); | ||
} | ||
} | ||
|
||
return exportTypes; | ||
} |
40 changes: 40 additions & 0 deletions
40
packages/graphql-codegen-typed-document-nodes/src/visitor.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import { | ||
BaseDocumentsVisitor, | ||
getConfigValue, | ||
type ParsedDocumentsConfig, | ||
type RawDocumentsConfig, | ||
} from "@graphql-codegen/visitor-plugin-common"; | ||
import { GraphQLSchema, type OperationDefinitionNode } from "graphql"; | ||
import { pascalCase } from "change-case-all"; | ||
|
||
export class TypeScriptDocumentsVisitor extends BaseDocumentsVisitor { | ||
constructor(schema: GraphQLSchema, config: RawDocumentsConfig) { | ||
super( | ||
config, | ||
{ | ||
nonOptionalTypename: getConfigValue(config.nonOptionalTypename, false), | ||
preResolveTypes: getConfigValue(config.preResolveTypes, true), | ||
mergeFragmentTypes: getConfigValue(config.mergeFragmentTypes, false), | ||
} as ParsedDocumentsConfig, | ||
schema, | ||
); | ||
} | ||
|
||
getOperationName(operationNode: OperationDefinitionNode): string { | ||
return this.convertName(operationNode, { | ||
suffix: this._parsedConfig.operationResultSuffix, | ||
}); | ||
} | ||
|
||
getOperationResultType(operationNode: OperationDefinitionNode): string { | ||
const operationType: string = pascalCase(operationNode.operation); | ||
const operationTypeSuffix = this.getOperationSuffix( | ||
operationNode, | ||
operationType, | ||
); | ||
|
||
return this.convertName(operationNode, { | ||
suffix: operationTypeSuffix + this._parsedConfig.operationResultSuffix, | ||
}); | ||
} | ||
} |
16 changes: 16 additions & 0 deletions
16
packages/graphql-codegen-typed-document-nodes/tsconfig.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
{ | ||
"extends": "@wroud/tsconfig/tsconfig.json", | ||
"compilerOptions": { | ||
"tsBuildInfoFile": "./lib/.tsbuildinfo", | ||
"rootDir": "src", | ||
"rootDirs": [ | ||
"src" | ||
], | ||
"outDir": "lib", | ||
"incremental": true, | ||
"composite": true | ||
}, | ||
"include": [ | ||
"src" | ||
] | ||
} |
Oops, something went wrong.