Skip to content

Commit 21a2723

Browse files
feat: AjvSchema.createFromZod
1 parent 5068403 commit 21a2723

2 files changed

Lines changed: 13 additions & 11 deletions

File tree

‎packages/nodejs-lib/src/jwt/jwt.service.test.ts‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,11 @@ interface Data {
1717
num: number
1818
}
1919

20-
const dataZodSchema = z.object({
21-
accountId: z.string(),
22-
num: z.number(),
23-
})
24-
25-
const dataSchema = AjvSchema.create<Data>(
26-
z.toJSONSchema(dataZodSchema, { target: 'draft-7' }) as any,
20+
const dataSchema = AjvSchema.createFromZod<Data>(
21+
z.object({
22+
accountId: z.string(),
23+
num: z.number(),
24+
}),
2725
)
2826

2927
const data1: Data = {

‎packages/nodejs-lib/src/validation/ajv/ajvSchema.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import type { JsonSchema, JsonSchemaBuilder } from '@naturalcycles/js-lib/json-s
88
import { JsonSchemaAnyBuilder } from '@naturalcycles/js-lib/json-schema'
99
import { _filterNullishValues } from '@naturalcycles/js-lib/object'
1010
import { _substringBefore } from '@naturalcycles/js-lib/string'
11+
import { z, type ZodType } from '@naturalcycles/js-lib/zod'
1112
import type { Ajv } from 'ajv'
1213
import { _inspect } from '../../string/inspect.js'
1314
import { AjvValidationError } from './ajvValidationError.js'
@@ -55,8 +56,6 @@ export interface AjvSchemaCfg {
5556
/**
5657
* On creation - compiles ajv validation function.
5758
* Provides convenient methods, error reporting, etc.
58-
*
59-
* @experimental
6059
*/
6160
export class AjvSchema<T = unknown> {
6261
private constructor(
@@ -81,7 +80,7 @@ export class AjvSchema<T = unknown> {
8180
*/
8281
static createLazy<T>(
8382
schema: JsonSchemaBuilder<T> | JsonSchema<T> | AjvSchema<T>,
84-
cfg: Partial<AjvSchemaCfg> = {},
83+
cfg?: Partial<AjvSchemaCfg>,
8584
): AjvSchema<T> {
8685
return AjvSchema.create(schema, {
8786
lazy: true,
@@ -100,7 +99,7 @@ export class AjvSchema<T = unknown> {
10099
*/
101100
static create<T>(
102101
schema: JsonSchemaBuilder<T> | JsonSchema<T> | AjvSchema<T>,
103-
cfg: Partial<AjvSchemaCfg> = {},
102+
cfg?: Partial<AjvSchemaCfg>,
104103
): AjvSchema<T> {
105104
if (schema instanceof AjvSchema) return schema
106105
if (schema instanceof JsonSchemaAnyBuilder) {
@@ -109,6 +108,11 @@ export class AjvSchema<T = unknown> {
109108
return new AjvSchema<T>(schema as JsonSchema<T>, cfg)
110109
}
111110

111+
static createFromZod<T>(zodSchema: ZodType<T>, cfg?: Partial<AjvSchemaCfg>): AjvSchema<T> {
112+
const jsonSchema = z.toJSONSchema(zodSchema, { target: 'draft-7' })
113+
return new AjvSchema<T>(jsonSchema as JsonSchema<T>, cfg)
114+
}
115+
112116
readonly cfg: AjvSchemaCfg
113117

114118
/**

0 commit comments

Comments
 (0)