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

New plugin for typed-document-node #4392

Merged
merged 2 commits into from Jul 19, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -0,0 +1 @@
module.exports = require('../../../../jest.project')({ dirname: __dirname });
36 changes: 36 additions & 0 deletions packages/plugins/typescript/typed-document-node/package.json
@@ -0,0 +1,36 @@
{
"name": "@graphql-codegen/typed-document-node",
"version": "1.17.0",
"description": "GraphQL Code Generator plugin for generating ready-to-use TypedDocumentNode based on GraphQL operations",
"repository": {
"type": "git",
"url": "https://github.com/dotansimha/graphql-code-generator.git",
"directory": "packages/plugins/typescript/apollo-angular"
},
"license": "MIT",
"scripts": {
"lint": "eslint **/*.ts",
"test": "jest --no-watchman --config ../../../../jest.config.js",
"prepack": "bob prepack"
},
"peerDependencies": {
"graphql": "^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0"
},
"dependencies": {
"change-case": "4.1.1",
"@graphql-codegen/plugin-helpers": "1.17.0",
"tslib": "~2.0.0"
},
"main": "dist/index.cjs.js",
"module": "dist/index.esm.js",
"typings": "dist/index.d.ts",
"typescript": {
"definition": "dist/index.d.ts"
},
"buildOptions": {
"input": "./src/index.ts"
},
"publishConfig": {
"access": "public"
}
}
34 changes: 34 additions & 0 deletions packages/plugins/typescript/typed-document-node/src/index.ts
@@ -0,0 +1,34 @@
import { Types, PluginValidateFn, PluginFunction } from '@graphql-codegen/plugin-helpers';
import { parse, GraphQLSchema, OperationDefinitionNode } from 'graphql';
import { pascalCase } from 'change-case';
import { extname } from 'path';

export const plugin: PluginFunction<{}> = (schema: GraphQLSchema, documents: Types.DocumentFile[], config) => {
return {
prepend: [`import { TypedDocumentNode } from '@graphql-typed-document-node/core';`],
content: documents
.map(docFile => {
const operation = docFile.document.definitions[0] as OperationDefinitionNode;
const resultTypeName = pascalCase(operation.name.value) + pascalCase(operation.operation);
const variablesTypeName = pascalCase(operation.name.value) + pascalCase(operation.operation) + 'Variables';

return `export const ${operation.name.value}${pascalCase(
operation.operation
)}: TypedDocumentNode<${resultTypeName}, ${variablesTypeName}> = ${JSON.stringify(
parse(docFile.rawSDL, { noLocation: true })
)};`;
})
.join('\n'),
};
};

export const validate: PluginValidateFn<any> = async (
schema: GraphQLSchema,
documents: Types.DocumentFile[],
config,
outputFile: string
) => {
if (extname(outputFile) !== '.ts') {
throw new Error(`Plugin "typed-document-node" requires extension to be ".ts"!`);
}
};
1 change: 1 addition & 0 deletions tsconfig.json
Expand Up @@ -53,6 +53,7 @@
"@graphql-codegen/typescript-resolvers": ["packages/plugins/typescript/resolvers/src/index.ts"],
"@graphql-codegen/typescript-stencil-apollo": ["packages/plugins/typescript/stencil-apollo/src/index.ts"],
"@graphql-codegen/typescript-type-graphql": ["packages/plugins/typescript/type-graphql/src/index.ts"],
"@graphql-codegen/typed-document-node": ["packages/plugins/typescript/typed-document-node/src/index.ts"],
"@graphql-codegen/typescript": ["packages/plugins/typescript/typescript/src/index.ts"],
"@graphql-codegen/typescript-urql": ["packages/plugins/typescript/urql/src/index.ts"],
"@graphql-codegen/typescript-vue-apollo": ["packages/plugins/typescript/vue-apollo/src/index.ts"],
Expand Down
13 changes: 7 additions & 6 deletions website/docs/generated-config/c-sharp-operations.md
Expand Up @@ -10,30 +10,31 @@ This plugin generates C# `class` based on your GraphQL operations.

## API Reference

### `namedClient`
### `namespaceName`

type: `string`
default: `GraphQLCodeGen`

Defined the global value of `namedClient`.
Allow you to customize the namespace name.

#### Usage Examples

```yml
config:
namedClient: 'customName'
namespaceName: MyCompany.MyNamespace
```

### `serviceName`
### `namedClient`

type: `string`

Defined the global value of `serviceName`.
Defined the global value of `namedClient`.

#### Usage Examples

```yml
config:
serviceName: 'MySDK'
namedClient: 'customName'
```

### `querySuffix`
Expand Down
18 changes: 18 additions & 0 deletions website/docs/generated-config/c-sharp.md
Expand Up @@ -26,6 +26,24 @@ Overrides the default value of enum values declared in your GraphQL schema.
A: 'foo'
```

### `namespaceName`

type: `string`
default: `GraphQLCodeGen`

Allow you to customize the namespace name.

#### Usage Examples

```yml
generates:
src/main/c-sharp/my-org/my-app/MyTypes.cs:
plugins:
- c-sharp
config:
namespaceName: MyCompany.MyNamespace
```

### `className`

type: `string`
Expand Down
15 changes: 15 additions & 0 deletions website/docs/generated-config/flow-operations.md
Expand Up @@ -84,6 +84,21 @@ plugins
preResolveTypes: true
```

### `skipTypeNameForRoot`

type: `boolean`
default: `false`

Avoid adding `__typename` for root types. This is ignored when a selection explictly specifies `__typename`.

#### Usage Examples

```yml
plugins
config:
skipTypeNameForRoot: true
```

### `globalNamespace`

type: `boolean`
Expand Down
25 changes: 25 additions & 0 deletions website/docs/generated-config/flow-resolvers.md
Expand Up @@ -267,6 +267,31 @@ default: `false`
Generates immutable types by adding `readonly` to properties and uses `ReadonlyArray`.


### `namespacedImportName`

type: `string`
default: `''`

Prefixes all GraphQL related generated types with that value, as namespaces import.
You can use this featuere to allow seperation of plugins to different files.


### `resolverTypeSuffix`

type: `string`
default: `Resolvers`

Suffix we add to each generated type resolver.


### `allResolversTypeName`

type: `string`
default: `Resolvers`

The type name to use when exporting all resolvers signature as unified type.


### `scalars`

type: `ScalarsMap`
Expand Down
4 changes: 2 additions & 2 deletions website/docs/generated-config/named-operations-object.md
Expand Up @@ -22,7 +22,7 @@ generates:
path/to/file.ts:
plugins:
- typescript
- named-operations-object
- typescript-named-operations-object
config:
identifierName: ListAllOperations
```
```
Expand Up @@ -28,7 +28,6 @@ between generated types.
generates: src/api/user-service/queries.d.ts
documents: src/api/user-service/queries.graphql
plugins:
- typescript
- typescript-graphql-files-modules
config:
# resulting module definition path glob: "*\/api/user-service/queries.graphql"
Expand Down
15 changes: 15 additions & 0 deletions website/docs/generated-config/typescript-operations.md
Expand Up @@ -126,6 +126,21 @@ plugins
preResolveTypes: true
```

### `skipTypeNameForRoot`

type: `boolean`
default: `false`

Avoid adding `__typename` for root types. This is ignored when a selection explictly specifies `__typename`.

#### Usage Examples

```yml
plugins
config:
skipTypeNameForRoot: true
```

### `operationResultSuffix`

type: `string`
Expand Down
53 changes: 53 additions & 0 deletions website/docs/generated-config/typescript-resolvers.md
Expand Up @@ -120,6 +120,34 @@ path/to/file.ts:
) => Promise<TResult> | TResult;
```

### `allowParentTypeOverride`

type: `boolean`

Allow you to override the `ParentType` generic in each resolver, by avoid enforcing the base type of the generated generic type.

This will generate `ParentType = Type` instead of `ParentType extends Type = Type` in each resolver.

#### Usage Examples

```yml
config:
allowParentTypeOverride: true
```

### `optionalInfoArgument`

type: `boolean`

Sets `info` argument of resolver function to be optional field. Useful for testing.

#### Usage Examples

```yml
config:
optionalInfoArgument: true
```

### `addUnderscoreToArgsType`

type: `boolean`
Expand Down Expand Up @@ -373,6 +401,31 @@ default: `false`
Generates immutable types by adding `readonly` to properties and uses `ReadonlyArray`.


### `namespacedImportName`

type: `string`
default: `''`

Prefixes all GraphQL related generated types with that value, as namespaces import.
You can use this featuere to allow seperation of plugins to different files.


### `resolverTypeSuffix`

type: `string`
default: `Resolvers`

Suffix we add to each generated type resolver.


### `allResolversTypeName`

type: `string`
default: `Resolvers`

The type name to use when exporting all resolvers signature as unified type.


### `scalars`

type: `ScalarsMap`
Expand Down
47 changes: 47 additions & 0 deletions website/docs/plugins/typed-document-node.md
@@ -0,0 +1,47 @@
---
id: typed-document-node
title: TypedDocumentNode
---

{@import ../plugins/client-note.md}

This plugins generates a ready-to-use `TypedDocumentNode` (a combination of pre-compiled `DocumentNode` and the TypeScript signature it represents).

For information about the setup and usage of `TypedDocumentNode`, [please refer to the library's documentation](https://github.com/dotansimha/graphql-typed-document-node).

> This plugins requires `typescript` and `typescript-operations` as siblings.

### Usage example

```yaml
schema: SCHEMA_FILE_OR_ENDPOINT_HERE
documents: "./src/**/*.graphql"
generates:
./src/graphql-operations.ts:
plugins:
- typescript
- typescript-operations
- typed-document-node
```

The example about will generate `TypedDocumentNode` with the needed types built-in, for example:

```ts
// Represents the variables type of the operation - generated by `typescript` + `typescript-operations` plugins
export type RatesQueryVariables = Exact<{
currency: Scalars['String'];
}>;

// Represents the result type of the operation - generated by `typescript` + `typescript-operations` plugins
export type RatesQuery = (
{ __typename?: 'Query' }
& { rates?: Maybe<Array<Maybe<(
{ __typename?: 'ExchangeRate' }
& Pick<ExchangeRate, 'currency' | 'rate'>
)>>> }
);

// Generated by this plugin - creates a pre-compiled `DocumentNode` and passes result type and variables type as generics
export const ratesQuery: TypedDocumentNode<RatesQuery, RatesQueryVariables> = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{ ... ]};
```

1 change: 1 addition & 0 deletions website/package.json
Expand Up @@ -48,6 +48,7 @@
"@graphql-codegen/schema-ast": "1.17.0",
"@graphql-codegen/time": "1.17.0",
"@graphql-codegen/typescript": "1.17.0",
"@graphql-codegen/typed-document-node": "1.17.0",
"@graphql-codegen/typescript-apollo-angular": "1.17.0",
"@graphql-codegen/typescript-compatibility": "1.17.0",
"@graphql-codegen/typescript-generic-sdk": "1.17.0",
Expand Down
1 change: 1 addition & 0 deletions website/sidebars.js
Expand Up @@ -28,6 +28,7 @@ module.exports = {
'plugins/typescript',
'plugins/typescript-operations',
'plugins/typescript-resolvers',
'plugins/typed-document-node',
'plugins/typescript-graphql-request',
'plugins/typescript-react-apollo',
'plugins/typescript-vue-apollo',
Expand Down
2 changes: 1 addition & 1 deletion website/src/components/live-demo/LiveDemo.js
Expand Up @@ -91,7 +91,7 @@ export const LiveDemo = () => {
menu: styles => ({ ...styles, ...(isDarkTheme ? { backgroundColor: 'black' } : {}) }),
control: styles => ({ ...styles, ...(isDarkTheme ? { backgroundColor: 'black' } : {}) }),
container: styles => ({ ...styles, display: 'inline-block', width: '100%', textAlign: 'left' }),
option: styles => ({ ...styles, fontSize: 13 }),
option: (styles, { isFocused }) => ({ ...styles, fontSize: 13, ...(isDarkTheme && isFocused ? { backgroundColor: 'gray' } : {}) }),
singleValue: styles => ({ ...styles, width: '100%', ...(isDarkTheme ? { color: 'white' } : {}) }),
}}
isMulti={false}
Expand Down