Skip to content

Commit

Permalink
Fix legacy type into zod fallback
Browse files Browse the repository at this point in the history
  • Loading branch information
G4brym committed Jun 9, 2024
1 parent 7d8f4ef commit 4711c09
Show file tree
Hide file tree
Showing 7 changed files with 29 additions and 25 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"package": "npm run build && npm pack",
"test:cov": "jest --coverage --no-cache --runInBand",
"addscope": "node config/packagejson name @cloudflare/itty-router-openapi",
"prettify": "prettier --check src tests README.md || (prettier -w src tests README.md)",
"prettify": "prettier --check src tests README.md || (prettier -w src tests README.md; exit 1)",
"lint": "npm run prettify",
"prepare": "husky install",
"test": "jest --no-cache --runInBand --config jestconfig.json --verbose",
Expand Down
2 changes: 1 addition & 1 deletion rollup.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@ export default defineConfig({
],
}),
],
external: ['itty-router', 'zod', '@asteasolutions/zod-to-openapi', 'js-yaml'],
external: ['itty-router', 'zod', '@asteasolutions/zod-to-openapi', 'js-yaml', 'openapi3-ts'],
})
3 changes: 1 addition & 2 deletions src/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
} from '@asteasolutions/zod-to-openapi'
import { OpenAPIRegistryMerger } from './zod/registry'
import { z } from 'zod'
import { OpenAPIObject } from 'openapi3-ts/oas31'
import yaml from 'js-yaml'

export type OpenAPIRouterType<M> = {
Expand Down Expand Up @@ -95,7 +94,7 @@ export class OpenAPIHandler {
}
}

getGeneratedSchema(): OpenAPIObject {
getGeneratedSchema() {
let openapiGenerator: any = OpenApiGeneratorV31
if (this.options?.openapiVersion === '3')
openapiGenerator = OpenApiGeneratorV3
Expand Down
30 changes: 18 additions & 12 deletions src/parameters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import {
import { z } from 'zod'
import { isSpecificZodType, legacyTypeIntoZod } from './zod/utils'
import { RouteParameter } from '@asteasolutions/zod-to-openapi/dist/openapi-registry'
import { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi'

extendZodWithOpenApi(z)
export function convertParams<M = z.ZodType>(field: any, params: any): M {
params = params || {}
if (params.required === false)
Expand Down Expand Up @@ -44,19 +46,13 @@ export function Obj(fields: object, params?: ParameterType): z.ZodObject<any> {
}

export function Num(params?: ParameterType): z.ZodNumber {
return convertParams<z.ZodNumber>(
z.number().or(z.string()).pipe(z.number()),
params
).openapi({
return convertParams<z.ZodNumber>(z.number(), params).openapi({
type: 'number',
})
}

export function Int(params?: ParameterType): z.ZodNumber {
return convertParams<z.ZodNumber>(
z.number().int().or(z.string()).pipe(z.number()),
params
).openapi({
return convertParams<z.ZodNumber>(z.number().int(), params).openapi({
type: 'integer',
})
}
Expand Down Expand Up @@ -184,7 +180,8 @@ export function coerceInputs(
}

const params: Record<string, any> = {}
for (let [key, value] of data.entries()) {
const entries = data.entries ? data.entries() : Object.entries(data)
for (let [key, value] of entries) {
// Query, path and headers can be empty strings, that should equal to null as nothing was provided
if (value === '') {
// @ts-ignore
Expand Down Expand Up @@ -223,11 +220,20 @@ export function coerceInputs(
if (_val === 'true' || _val === 'false') {
params[key] = _val === 'true'
}
} else if (isSpecificZodType(innerType, 'ZodNumber')) {
} else if (
isSpecificZodType(innerType, 'ZodNumber') ||
innerType instanceof z.ZodNumber
) {
params[key] = parseFloat(params[key])
} else if (isSpecificZodType(innerType, 'ZodBigInt')) {
} else if (
isSpecificZodType(innerType, 'ZodBigInt') ||
innerType instanceof z.ZodBigInt
) {
params[key] = parseInt(params[key])
} else if (isSpecificZodType(innerType, 'ZodDate')) {
} else if (
isSpecificZodType(innerType, 'ZodDate') ||
innerType instanceof z.ZodDate
) {
params[key] = new Date(params[key])
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ export class OpenAPIRoute {

static isRoute = true

private args: any[] = [] // Args the execute() was called with
private validatedData: any = undefined // this acts as a cache, in case the users calls the validate method twice
args: any[] = [] // Args the execute() was called with
validatedData: any = undefined // this acts as a cache, in case the users calls the validate method twice
params: RouteOptions
schema: OpenAPIRouteSchema = {}

Expand Down
2 changes: 2 additions & 0 deletions src/zod/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ export class OpenAPIRegistryMerger extends OpenAPIRegistry {
public _definitions: OpenAPIDefinitions[] = []

merge(registry: OpenAPIRegistryMerger): void {
if (!registry || !registry._definitions) return

for (const definition of registry._definitions) {
this._definitions.push({ ...definition })
}
Expand Down
11 changes: 4 additions & 7 deletions src/zod/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ export function isSpecificZodType(field: any, typeName: string): boolean {
(field.unwrap && field.unwrap()._def.typeName) === typeName ||
(field.unwrap &&
field.unwrap().unwrap &&
field.unwrap().unwrap()._def.typeName) === typeName
field.unwrap().unwrap()._def.typeName) === typeName ||
field._def.innerType?._def?.innerType?._def?.typeName === typeName
)
}

Expand All @@ -41,11 +42,6 @@ export function legacyTypeIntoZod(type: any, params?: any): z.ZodType {
return type
}

// Legacy support
if (type.generator === true) {
return new type(params) as z.ZodType
}

if (type === String) {
return Str(params)
}
Expand Down Expand Up @@ -86,5 +82,6 @@ export function legacyTypeIntoZod(type: any, params?: any): z.ZodType {
return Obj(type, params)
}

throw new Error(`${type} not implemented`)
// Legacy support
return type(params)
}

0 comments on commit 4711c09

Please sign in to comment.