• Stars
    star
    313
  • Rank 133,714 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 3 years ago
  • Updated 27 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

GraphQL Code Generator plugin to generate form validation schema from your GraphQL schema

graphql-codegen-typescript-validation-schema

Test npm version

GraphQL code generator plugin to generate form validation schema from your GraphQL schema.

Quick Start

Start by installing this plugin and write simple plugin config;

$ npm i graphql-codegen-typescript-validation-schema
generates:
  path/to/graphql.ts:
    plugins:
      - typescript
      - typescript-validation-schema # specify to use this plugin
    config:
      # You can put the config for typescript plugin here
      # see: https://www.graphql-code-generator.com/plugins/typescript
      strictScalars: true
      # Overrides built-in ID scalar to both input and output types as string.
      # see: https://the-guild.dev/graphql/codegen/plugins/typescript/typescript#scalars
      scalars:
        ID: string
      # You can also write the config for this plugin together
      schema: yup # or zod

It is recommended to write scalars config for built-in type ID, as in the yaml example shown above. For more information: #375

You can check example directory if you want to see more complex config example or how is generated some files.

The Q&A for each schema is written in the README in the respective example directory.

Config API Reference

schema

type: ValidationSchema default: 'yup'

Specify generete validation schema you want.

You can specify yup or zod or myzod.

generates:
  path/to/graphql.ts:
    plugins:
      - typescript
      - typescript-validation-schema
    config:
      schema: yup

importFrom

type: string

When provided, import types from the generated typescript types file path. if not given, omit import statement.

generates:
  path/to/graphql.ts:
    plugins:
      - typescript
  path/to/validation.ts:
    plugins:
      - typescript-validation-schema
    config:
      importFrom: ./graphql # path for generated ts code

Then the generator generates code with import statement like below.

import { GeneratedInput } from './graphql'

/* generates validation schema here */

useTypeImports

type: boolean default: false

Will use import type {} rather than import {} when importing generated TypeScript types. This gives compatibility with TypeScript's "importsNotUsedAsValues": "error" option. Should used in conjunction with importFrom option.

typesPrefix

type: string default: (empty)

Prefixes all import types from generated typescript type.

generates:
  path/to/graphql.ts:
    plugins:
      - typescript
  path/to/validation.ts:
    plugins:
      - typescript-validation-schema
    config:
      typesPrefix: I
      importFrom: ./graphql # path for generated ts code

Then the generator generates code with import statement like below.

import { IGeneratedInput } from './graphql'

/* generates validation schema here */

typesSuffix

type: string default: (empty)

Suffixes all import types from generated typescript type.

generates:
  path/to/graphql.ts:
    plugins:
      - typescript
  path/to/validation.ts:
    plugins:
      - typescript-validation-schema
    config:
      typesSuffix: I
      importFrom: ./graphql # path for generated ts code

Then the generator generates code with import statement like below.

import { GeneratedInputI } from './graphql'

/* generates validation schema here */

enumsAsTypes

type: boolean default: false

Generates enum as TypeScript type instead of enum.

notAllowEmptyString

type: boolean default: false

Generates validation string schema as do not allow empty characters by default.

scalarSchemas

type: ScalarSchemas

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

yup schema

config:
  schema: yup
  scalarSchemas:
    Date: yup.date()
    Email: yup.string().email()

zod schema

config:
  schema: zod
  scalarSchemas:
    Date: z.date()
    Email: z.string().email()

withObjectType

type: boolean default: false

Generates validation schema with GraphQL type objects. But excludes Query, Mutation, Subscription objects.

It is currently added for the purpose of using simple objects. See also #20, #107.

This option currently does not support fragment generation. If you are interested, send me PR would be greatly appreciated!

validationSchemaExportType

type: ValidationSchemaExportType default: 'function'

Specify validation schema export type.

directives

type: DirectiveConfig

Generates validation schema with more API based on directive schema. For example, yaml config and GraphQL schema is here.

input ExampleInput {
  email: String! @required(msg: "Hello, World!") @constraint(minLength: 50, format: "email")
  message: String! @constraint(startsWith: "Hello")
}

yup schema

generates:
  path/to/graphql.ts:
    plugins:
      - typescript
      - typescript-validation-schema
    config:
      schema: yup
      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
        required:
          msg: required
        constraint:
          minLength: min
          # Replace $1 with specified `startsWith` argument value of the constraint directive
          startsWith: ["matches", "/^$1/"]
          format:
            email: email

Then generates yup validation schema like below.

export function ExampleInputSchema(): yup.SchemaOf<ExampleInput> {
  return yup.object({
    email: yup.string().defined().required("Hello, World!").min(50).email(),
    message: yup.string().defined().matches(/^Hello/)
  })
}

zod schema

generates:
  path/to/graphql.ts:
    plugins:
      - typescript
      - typescript-validation-schema
    config:
      schema: zod
      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: min
          # Replace $1 with specified `startsWith` argument value of the constraint directive
          startsWith: ["regex", "/^$1/", "message"]
          format:
            email: email

Then generates zod validation schema like below.

export function ExampleInputSchema(): z.ZodSchema<ExampleInput> {
  return z.object({
    email: z.string().min(50).email(),
    message: z.string().regex(/^Hello/, "message")
  })
}

other schema

Please see example directory.

Notes

Their is currently a compatibility issue with the client-preset. A workaround for this is to split the generation into two (one for client-preset and one for typescript-validation-schema).

generates:
  path/to/graphql.ts:
    plugins:
      - typescript-validation-schema
  /path/to/graphql/:
    preset: 'client',
      plugins:
      ...

More Repositories

1

pget

The fastest, resumable file download client
Go
1,047
star
2

vz

Create virtual machines and run Linux-based operating systems in Go using Apple Virtualization.framework.
Go
569
star
3

go-generics-cache

A key:value store/cache library written in Go generics. LRU, LFU, FIFO, MRU, Clock support.
Go
458
star
4

synchro

🕰️ Synchro: Timezone-typesafe date and time framework for Go. 🌟 Star to support our work!
Go
260
star
5

Neo-cowsay

🐮 cowsay is reborn. Neo Cowsay has written in Go.
Go
246
star
6

gqldoc

The easiest way to make API documents for GraphQL
Go
192
star
7

dd

Data Dumper library dumps any data as valid syntax in Go
Go
185
star
8

firebase-auth-cloudflare-workers

TypeScript
131
star
9

battery

Display your battery status on terminal (or tmux) written by Go
Go
70
star
10

golet

*.go file as a mini supervisor
Go
60
star
11

funcy-mock

funcy-mock generates mock file from interface go file
Go
52
star
12

shibafu

Shibafu Programming Language wwwwwwwwwww
Go
41
star
13

container-registry

container-registry
Go
29
star
14

puipui-linux

So tiny linux for testing virtualization (Virtual I/O aka VIRTIO) purpose
Shell
24
star
15

fast-service

fast-service is opensource speedtest service written in Go
Go
24
star
16

testing-grpc

go-grpc server, client for onboarding
Go
23
star
17

go-install-tools

Install All go-tools at one time!!
Go
22
star
18

sqlx-transactionmanager

Transaction manager for github.com/jmoiron/sqlx
Go
22
star
19

White-MobileTerminal

Supports ios versions from 7.0 to 8.1 !!
C++
20
star
20

go-version-update

Update the version string of your go project.
Go
20
star
21

echo-static

Static middleware for echo web framework(golang)
Go
19
star
22

sigctx

context with signal in golang
Go
19
star
23

retrygroup

Package retrygroup provides synchronization, Context cancelation for groups of retry goroutines working on subtasks of a common task.
Go
17
star
24

sqb

⚡Blazing fast, Flexible, SQL Query Builder for Go
Go
17
star
25

gvisor-vmnet

vmnet based gvisor tcpip stack
Go
11
star
26

auto-milestone-binder

An action for binding milestone to some PR or some issues
TypeScript
8
star
27

dotfiles

大事なdotを管理してます👍
Shell
8
star
28

grpc-edge-gateway

gRPC Gateway on the edge functions
TypeScript
7
star
29

deno-context

🦕【Deno】Propagate deadlines, a cancellation and other request-scoped values to multiple promise.
TypeScript
6
star
30

neo-cowsay-action

🐮 GitHub action for cowsay lovers
Shell
5
star
31

takopi

っピ!
Go
5
star
32

socks5

socks5 server implemented by Go
Go
5
star
33

go-emojipacks

https://github.com/lambtron/emojipacks has been stopped. A new emojipacks has been implemented by Go
Go
5
star
34

saltissimo

Easy generate, easy compare hash using pbdkf2
Go
5
star
35

exit

Error makes exit code meaningful
Go
5
star
36

gqldoc-actions

JavaScript
5
star
37

code-hex.github.io

My homepage
TypeScript
5
star
38

Text-Shirasu

Wrapped Text::MeCab in Perl
Perl
5
star
39

go-async

More Easy, more readable sync.WaitGroup
Go
5
star
40

twippai

Perl、Python、RubyでTwitterからたくさんのおっぱいをダウンロードする
Go
4
star
41

go-infinity-channel

Provides an infinitely queueing channel.
Go
4
star
42

go-github-token

Very easy to get github access token library written in Go
Go
3
star
43

arm64-docker-mysql

Shell
3
star
44

uploader

uploader by grpc go
Go
3
star
45

HotKeyCapture

This is a sandboxed of custom global hotkeys in Swift using HotKeyCapture
Swift
3
star
46

ssh-gpt

Fictitious SSH Server - Powered by OpenAI ChatGPT
Go
3
star
47

chair

isucon tool
Go
2
star
48

Text-CaboCha

Alternate Text-CaboCha Binding
Perl
2
star
49

gpl

Update multiple local repositories with parallel
Go
2
star
50

p5-App-Format

Format for perl code. It's like a gofmt.
Perl
2
star
51

Card

テストを乗り切るために開発されたアプリ
Swift
2
star
52

m1-docker

Please following this URL
Go
2
star
53

network

Asynchronous Networking Patterns
Go
2
star
54

vegeta

Project to collect large amounts of vegetable data using IoT
Go
2
star
55

Algorithm-NaiveBayes-RandomForest

RandomForest with Algorithm::NaiveBayes in perl
Perl
1
star
56

go-groff

groff parser
Go
1
star
57

go-elisp

elisp implement by Go
Go
1
star
58

MyApplication

Implement NSApplication main-event-loop
Objective-C
1
star
59

first-label-interaction

Labeling actions for new comer
JavaScript
1
star
60

fmm

Friendly memory monitoring tool
C
1
star
61

touchbar-emoji

emoji on control strip
Objective-C
1
star
62

godzilla

Management tool for go
Go
1
star
63

alpine-chrome

Chrome Headless docker images built upon alpine
Dockerfile
1
star
64

ghp

Create a new project on the ghq root
Go
1
star
65

IF

Ternary operator package for Go
Go
1
star
66

Color-Capture

Color Capture is PopClip Extension
Objective-C
1
star
67

go-riscv

Go
1
star
68

p5-Shell-Tiny

Very tiny shell written in Perl5
Perl
1
star
69

august

gRPC to RESTful or Protobuf on HTTP proxy for microservices
1
star
70

tenpuzzle

Tenpuzzle - Find the solution of the 10 puzzles in Genetic Algorithm
Go
1
star
71

p5-XS-Closure-Example

Example for how to make a closure on XS
C
1
star
72

p5-List-Flatten-XS

Fast flatten
Perl
1
star