Skip to content

support valibot #660

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

Closed
wants to merge 18 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
23 changes: 23 additions & 0 deletions codegen.yml
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,26 @@ generates:
email: email
scalars:
ID: string
example/valibot/schemas.ts:
plugins:
- ./dist/main/index.js:
schema: valibot
importFrom: ../types
withObjectType: true
directives:
# Write directives like
#
# directive:
# arg1: schemaApi
# arg2: ["schemaApi2", "Hello $1"]
#
# See more examples in `./tests/directive.spec.ts`
# https://github.com/Code-Hex/graphql-codegen-typescript-validation-schema/blob/main/tests/directive.spec.ts
constraint:
minLength: minLength
# Replace $1 with specified `startsWith` argument value of the constraint directive
startsWith: [regex, /^$1/, message]
format:
email: email
scalars:
ID: string
4 changes: 4 additions & 0 deletions example/valibot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Tips for valibot schema

## How to overwrite generated schema?

104 changes: 104 additions & 0 deletions example/valibot/schemas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import * as v from 'valibot'
import { AttributeInput, ButtonComponentType, ComponentInput, DropDownComponentInput, EventArgumentInput, EventInput, EventOptionType, HttpInput, HttpMethod, LayoutInput, PageInput, PageType } from '../types'

export const ButtonComponentTypeSchema = v.enum_(ButtonComponentType);

export const EventOptionTypeSchema = v.enum_(EventOptionType);

export const HttpMethodSchema = v.enum_(HttpMethod);

export const PageTypeSchema = v.enum_(PageType);

export function AttributeInputSchema() {
return v.object({
key: v.nullish(v.string()),
val: v.nullish(v.string())
})
}

export function ComponentInputSchema(): v.GenericSchema<ComponentInput> {
return v.object({
child: v.lazy(() => v.nullish(ComponentInputSchema())),
childrens: v.nullish(v.array(v.lazy(() => v.nullable(ComponentInputSchema())))),
event: v.lazy(() => v.nullish(EventInputSchema())),
name: v.string(),
type: ButtonComponentTypeSchema
})
}

export function DropDownComponentInputSchema() {
return v.object({
dropdownComponent: v.lazy(() => v.nullish(ComponentInputSchema())),
getEvent: v.lazy(() => EventInputSchema())
})
}

export function EventArgumentInputSchema(): v.GenericSchema<EventArgumentInput> {
return v.object({
name: v.pipe(v.string(), v.minLength(5)),
value: v.pipe(v.string(), v.regex(/^foo/, "message"))
})
}

type Infer1 = v.InferOutput<ReturnType<typeof EventArgumentInputSchema>>;

const ESchema = v.object({
name: v.pipe(v.string(), v.minLength(5)),
value: v.pipe(v.string(), v.regex(/^foo/, "message"))
});

type Infer2 = v.InferOutput<typeof ESchema>;

// const obj = v.object({ value: v.pipe(v.string(), v.minLength(5)) })
// // const obj = v.pipe(v.string(), v.minLength(5));
// type Infer1 = v.InferOutput<typeof obj>;

// // const str2: v.ObjectSchema<Readonly<{ value: v.SchemaWithPipe<[v.StringSchema<undefined>, v.MinLengthAction<string, 5, undefined>]> }>, undefined> = v.object({ value: v.pipe(v.string(), v.minLength(5)) })
// // const str2: v.ObjectSchema<Readonly<{ value: Omit<v.GenericSchema<string>, '_types' | '_run'> }>, undefined> = v.object({ value: v.pipe(v.string(), v.minLength(5)) })
// // const str2: v.GenericSchema<string> = v.pipe(v.string(), v.minLength(5));
// const obj2: v.GenericSchema<{ value: string }> = v.object({ value: v.pipe(v.string(), v.minLength(5)) })
// type Infer2 = v.InferOutput<typeof obj2>;

// 型が一致しているか確認するためのチェック
export const typeCheck: Infer1 extends Infer2
? Infer2 extends Infer1
? true
: false
: false = true;


export function EventInputSchema() {
return v.object({
arguments: v.array(v.lazy(() => EventArgumentInputSchema())),
options: v.nullish(v.array(EventOptionTypeSchema))
})
}

export function HttpInputSchema() {
return v.object({
method: v.nullish(HttpMethodSchema),
url: v.any()
})
}

export function LayoutInputSchema() {
return v.object({
dropdown: v.lazy(() => v.nullish(DropDownComponentInputSchema()))
})
}

export function PageInputSchema() {
return v.object({
attributes: v.nullish(v.array(v.lazy(() => AttributeInputSchema()))),
date: v.nullish(v.any()),
height: v.number(),
id: v.string(),
layout: v.lazy(() => LayoutInputSchema()),
pageType: PageTypeSchema,
postIDs: v.nullish(v.array(v.string())),
show: v.boolean(),
tags: v.nullish(v.array(v.nullable(v.string()))),
title: v.string(),
width: v.number()
})
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
"ts-dedent": "^2.2.0",
"ts-jest": "29.1.3",
"typescript": "5.4.5",
"valibot": "0.31.0-rc.5",
"vitest": "^1.0.0",
"yup": "1.4.0",
"zod": "3.23.8"
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { TypeScriptPluginConfig } from '@graphql-codegen/typescript';

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

export interface DirectiveConfig {
Expand Down
38 changes: 35 additions & 3 deletions src/directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,11 +115,44 @@ export function buildApi(config: FormattedDirectiveConfig, directives: ReadonlyA
.map((directive) => {
const directiveName = directive.name.value;
const argsConfig = config[directiveName];
return buildApiFromDirectiveArguments(argsConfig, directive.arguments ?? []);
return buildApiFromDirectiveArguments(argsConfig, directive.arguments ?? []).join('');
})
.join('')
}

// This function generates `[v.minLength(100), v.email()]`
// NOTE: valibot's API is not a method chain, so it is prepared separately from buildApi.
//
// config
// {
// 'constraint': {
// 'minLength': ['minLength', '$1'],
// 'format': {
// 'uri': ['url', '$2'],
// 'email': ['email', '$2'],
// }
// }
// }
//
// GraphQL schema
// ```graphql
// input ExampleInput {
// email: String! @required(msg: "message") @constraint(minLength: 100, format: "email")
// }
// ```
//
// FIXME: v.required() is not supported yet. v.required() is classified as `Methods` and must wrap the schema. ex) `v.required(v.object({...}))`
export function buildApiForValibot(config: FormattedDirectiveConfig, directives: ReadonlyArray<ConstDirectiveNode>): string[] {
return directives
.filter(directive => config[directive.name.value] !== undefined)
.map((directive) => {
const directiveName = directive.name.value;
const argsConfig = config[directiveName];
const apis = buildApiFromDirectiveArguments(argsConfig, directive.arguments ?? []);
return apis.map((api) => `v${api}`);
}).flat()
}

function buildApiSchema(validationSchema: string[] | undefined, argValue: ConstValueNode): string {
if (!validationSchema)
return '';
Expand All @@ -132,7 +165,7 @@ function buildApiSchema(validationSchema: string[] | undefined, argValue: ConstV
return `.${schemaApi}(${schemaApiArgs.join(', ')})`;
}

function buildApiFromDirectiveArguments(config: FormattedDirectiveArguments, args: ReadonlyArray<ConstArgumentNode>): string {
function buildApiFromDirectiveArguments(config: FormattedDirectiveArguments, args: ReadonlyArray<ConstArgumentNode>): string[] {
return args
.map((arg) => {
const argName = arg.name.value;
Expand All @@ -142,7 +175,6 @@ function buildApiFromDirectiveArguments(config: FormattedDirectiveArguments, arg

return buildApiSchema(validationSchema, arg.value);
})
.join('');
}

function buildApiFromDirectiveObjectArguments(config: FormattedDirectiveObjectArguments, argValue: ConstValueNode): string {
Expand Down
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { MyZodSchemaVisitor } from './myzod/index';
import type { SchemaVisitor } from './types';
import { YupSchemaVisitor } from './yup/index';
import { ZodSchemaVisitor } from './zod/index';
import { ValibotSchemaVisitor } from './valibot/index';

export const plugin: PluginFunction<ValidationSchemaPluginConfig, Types.ComplexPluginOutput> = (
schema: GraphQLSchema,
Expand All @@ -33,6 +34,8 @@ function schemaVisitor(schema: GraphQLSchema, config: ValidationSchemaPluginConf
return new ZodSchemaVisitor(schema, config);
else if (config?.schema === 'myzod')
return new MyZodSchemaVisitor(schema, config);
else if (config?.schema === 'valibot')
return new ValibotSchemaVisitor(schema, config);

return new YupSchemaVisitor(schema, config);
}
Expand Down
Loading