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

Adds support for maybeSchemaValue config #482

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 40 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
Start by installing this plugin and write simple plugin config;

```sh
$ npm i graphql-codegen-typescript-validation-schema
npm i graphql-codegen-typescript-validation-schema
```

```yml
Expand Down Expand Up @@ -154,6 +154,42 @@ type: `boolean` default: `false`

Generates enum as TypeScript `type` instead of `enum`.

### `maybeSchemaValue`

type: `MyZodNullishSchemaType` | `YupNullishSchemaType` | `ZodNullishSchemaType`

| schema | type | values | default |
| ------- | ------------------------ | ----------------------------------------------- | ------------ |
| `myzod` | `MyZodNullishSchemaType` | `never` | `never` |
| `yup` | `YupNullishSchemaType` | `'nullable'` \| `'optional'` \| `'notRequired'` | `'nullable'` |
| `zod` | `ZodNullishSchemaType` | `'nullable'` \| `'optional'` \| `'nullish'` | `'nullish'` |

Chooses which nullish schema to use

### `maybeSchemaValue`: myzod schema

```yml
config:
schema: myzod
# maybeSchemaValue: no valid options
```

#### `maybeSchemaValue`: yup schema

```yml
config:
schema: yup
maybeSchemaValue: nullable
```

#### `maybeSchemaValue`: zod schema

```yml
config:
schema: zod
maybeSchemaValue: optional
```

### `notAllowEmptyString`

type: `boolean` default: `false`
Expand All @@ -166,7 +202,7 @@ type: `ScalarSchemas`

Extends or overrides validation schema for the built-in scalars and custom GraphQL scalars.

#### yup schema
#### `scalarSchemas`: yup schema

```yml
config:
Expand All @@ -176,7 +212,7 @@ config:
Email: yup.string().email()
```

#### zod schema
#### `scalarSchemas`: zod schema

```yml
config:
Expand Down Expand Up @@ -310,4 +346,4 @@ generates:
preset: 'client',
plugins:
...
```
```
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
"README.md"
],
"scripts": {
"preinstall": "npx only-allow pnpm",
"type-check": "tsc --noEmit",
"type-check:yup": "tsc --strict --noEmit example/yup/schemas.ts",
"type-check:zod": "tsc --strict --noEmit example/zod/schemas.ts",
Expand Down
119 changes: 102 additions & 17 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { TypeScriptPluginConfig } from '@graphql-codegen/typescript';
import { type TypeScriptPluginConfig } from '@graphql-codegen/typescript'

export type ValidationSchema = 'yup' | 'zod' | 'myzod';
export type ValidationSchemaExportType = 'function' | 'const';

export const MyZodNullishSchemaTypes = [] as const;
export type MyZodNullishSchemaType = typeof MyZodNullishSchemaTypes[number];
export const ZodNullishSchemaTypes = ['nullable', 'optional', 'nullish'] as const;
export type ZodNullishSchemaType = typeof ZodNullishSchemaTypes[number];
export const YupNullishSchemaTypes = ['nullable', 'optional', 'notRequired'] as const;
export type YupNullishSchemaType = typeof YupNullishSchemaTypes[number];

export interface DirectiveConfig {
[directive: string]: {
[argument: string]: string | string[] | DirectiveObjectArguments;
Expand All @@ -17,23 +24,96 @@ interface ScalarSchemas {
[name: string]: string;
}

export interface ValidationSchemaPluginConfig extends TypeScriptPluginConfig {
interface MyZodValidationSchemaPluginConfig extends BaseValidationSchemaPluginConfig {
/**
* @description specify generate schema
* @default yup
* @exampleMarkdown
* ```yml
* generates:
* path/to/file.ts:
* plugins:
* - typescript
* - graphql-codegen-validation-schema
* config:
* schema: myzod
* ```
*/
schema?: 'myzod';
maybeSchemaValue?: MyZodNullishSchemaType
}

interface YupNullableSchemaTypesPluginConfig extends BaseValidationSchemaPluginConfig {
/**
* @description specify generate schema
* @default yup
*
* @exampleMarkdown
* ```yml
* generates:
* path/to/file.ts:
* plugins:
* - typescript
* - graphql-codegen-validation-schema
* config:
* schema: yup
* ```
*/
schema?: ValidationSchema;
* @description specify generate schema
* @default yup
* @exampleMarkdown
* ```yml
* generates:
* path/to/file.ts:
* plugins:
* - typescript
* - graphql-codegen-validation-schema
* config:
* schema: yup
* ```
*/
schema?: 'yup'
/**
* @description Set the schema value for nullish types.
* @default nullable
* @exampleMarkdown
* ```yml
* generates:
* path/to/file.ts:
* plugins:
* - typescript
* - graphql-codegen-validation-schema
* config:
* maybeSchemaValue: nullable
* ```
*
*
*/
maybeSchemaValue?: YupNullishSchemaType
}

interface ZodNullableSchemaTypesPluginConfig extends BaseValidationSchemaPluginConfig {
/**
* @description specify generate schema
* @default yup
* @exampleMarkdown
* ```yml
* generates:
* path/to/file.ts:
* plugins:
* - typescript
* - graphql-codegen-validation-schema
* config:
* schema: zod
* ```
*/
schema?: 'zod'
/**
* @description Set the schema value for nullish types.
* @default nullish
* @exampleMarkdown
* ```yml
* generates:
* path/to/file.ts:
* plugins:
* - typescript
* - graphql-codegen-validation-schema
* config:
* maybeSchemaValue: nullish
* ```
*
*
*/
maybeSchemaValue?: ZodNullishSchemaType
}

export interface BaseValidationSchemaPluginConfig extends TypeScriptPluginConfig {
/**
* @description import types from generated typescript type path
* if not given, omit import statement.
Expand Down Expand Up @@ -252,3 +332,8 @@ export interface ValidationSchemaPluginConfig extends TypeScriptPluginConfig {
*/
directives?: DirectiveConfig;
}

export type ValidationSchemaPluginConfig =
| MyZodValidationSchemaPluginConfig
| YupNullableSchemaTypesPluginConfig
| ZodNullableSchemaTypesPluginConfig
4 changes: 2 additions & 2 deletions src/yup/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ const generateFieldTypeYupSchema = (
if (isListType(type)) {
const gen = generateFieldTypeYupSchema(config, visitor, type.type, type);
if (!isNonNullType(parentType)) {
return `yup.array(${maybeLazy(type.type, gen)}).defined().nullable()`;
return `yup.array(${maybeLazy(type.type, gen)}).defined().${config.maybeSchemaValue ? config.maybeSchemaValue : 'nullable'}()`;
}
return `yup.array(${maybeLazy(type.type, gen)}).defined()`;
}
Expand All @@ -272,7 +272,7 @@ const generateFieldTypeYupSchema = (
if (typ?.astNode?.kind === 'InputObjectTypeDefinition') {
return `${gen}`;
}
return `${gen}.nullable()`;
return `${gen}.${config.maybeSchemaValue ? config.maybeSchemaValue : 'nullable'}()`;
}
console.warn('unhandled type:', type);
return '';
Expand Down
4 changes: 2 additions & 2 deletions src/zod/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ const generateFieldTypeZodSchema = (
if (!isNonNullType(parentType)) {
const arrayGen = `z.array(${maybeLazy(type.type, gen)})`;
const maybeLazyGen = applyDirectives(config, field, arrayGen);
return `${maybeLazyGen}.nullish()`;
return `${maybeLazyGen}.${config.maybeSchemaValue ? config.maybeSchemaValue : 'nullish'}()`;
}
return `z.array(${maybeLazy(type.type, gen)})`;
}
Expand All @@ -257,7 +257,7 @@ const generateFieldTypeZodSchema = (
if (isListType(parentType)) {
return `${appliedDirectivesGen}.nullable()`;
}
return `${appliedDirectivesGen}.nullish()`;
return `${appliedDirectivesGen}.${config.maybeSchemaValue ? config.maybeSchemaValue : 'nullish'}()`;
}
console.warn('unhandled type:', type);
return '';
Expand Down
34 changes: 34 additions & 0 deletions tests/myzod.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { buildClientSchema, buildSchema, introspectionFromSchema } from 'graphql';
import dedent from 'ts-dedent';

import { MyZodNullishSchemaTypes } from '../src/config';
import { plugin } from '../src/index';

describe('myzod', () => {
Expand Down Expand Up @@ -244,6 +245,39 @@ describe('myzod', () => {
expect(result.content).toContain('phrase: myzod.string()');
});

it('without maybeSchemaValue', async () => {
const schema = buildSchema(/* GraphQL */ `
input Say {
phrase: String
}
`)
const result = await plugin(
schema,
[],
{
schema: 'zod',
}
)
expect(result.content).toContain('phrase: z.string().nullish()')
})

it.each(MyZodNullishSchemaTypes)('with maybeSchemaValue: %s', async (maybeSchemaValue) => {
const schema = buildSchema(/* GraphQL */ `
input Say {
phrase: String
}
`)
const result = await plugin(
schema,
[],
{
schema: 'myzod',
maybeSchemaValue,
}
)
expect(result.content).toContain(`phrase: z.string().${ maybeSchemaValue }()`)
});

it('with enumsAsTypes', async () => {
const schema = buildSchema(/* GraphQL */ `
enum PageType {
Expand Down
34 changes: 34 additions & 0 deletions tests/yup.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { buildClientSchema, buildSchema, introspectionFromSchema } from 'graphql';
import dedent from 'ts-dedent';

import { YupNullishSchemaTypes } from '../src/config';
import { plugin } from '../src/index';

describe('yup', () => {
Expand Down Expand Up @@ -241,6 +242,39 @@ describe('yup', () => {
expect(result.content).toContain('phrase: yup.string().defined()');
});

it('without maybeSchemaValue', async () => {
const schema = buildSchema(/* GraphQL */ `
input Say {
phrase: String
}
`)
const result = await plugin(
schema,
[],
{
schema: 'zod',
}
)
expect(result.content).toContain('phrase: z.string().nullish()')
})

it.each(YupNullishSchemaTypes)('with maybeSchemaValue: %s', async (maybeSchemaValue) => {
const schema = buildSchema(/* GraphQL */ `
input Say {
phrase: String
}
`)
const result = await plugin(
schema,
[],
{
schema: 'yup',
maybeSchemaValue,
}
)
expect(result.content).toContain(`phrase: z.string().${ maybeSchemaValue }()`)
});

it('with enumsAsTypes', async () => {
const schema = buildSchema(/* GraphQL */ `
enum PageType {
Expand Down
Loading