Skip to content

Commit

Permalink
fix(openapi): resolve type errors (#784)
Browse files Browse the repository at this point in the history
  • Loading branch information
wilsonianb authored Nov 30, 2022
1 parent 96be5b0 commit 3a3f9e8
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 6 deletions.
11 changes: 10 additions & 1 deletion packages/openapi/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ const errorTransformer = (
}

const customFormats = {
uint64: function (input) {
uint64: function (input: string | number) {
try {
const value = BigInt(input)
return value >= BigInt(0)
Expand All @@ -173,3 +173,12 @@ const customFormats = {
}
}
}

interface ValidationError {
status?: number
errors: string[]
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const isValidationError = (err: any): err is ValidationError =>
Array.isArray(err.errors)
12 changes: 8 additions & 4 deletions packages/openapi/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { OpenAPI, RequestOptions } from './'
import { OpenAPI, RequestOptions, isValidationError } from './'

import Koa from 'koa'

Expand All @@ -19,16 +19,20 @@ export function createValidatorMiddleware<T extends Koa.ParameterizedContext>(
try {
if (validateRequest(ctx.request)) {
await next()
console.log('request=', ctx.request)
console.log('response=', ctx.response)
if (validateResponse && !validateResponse(ctx.response)) {
throw new Error('unreachable')
}
} else {
throw new Error('unreachable')
}
} catch (err) {
ctx.throw(err.status || 500, err.errors?.[0])
if (err instanceof Koa.HttpError) {
throw err
} else if (isValidationError(err)) {
ctx.throw(err.status ?? 500, err.errors[0])
} else {
ctx.throw(500)
}
}
}
}
3 changes: 2 additions & 1 deletion packages/openapi/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"declaration": true
"declaration": true,
"strict": true
},
"include": ["src/**/*"],
"exclude": ["**/*.test.ts"]
Expand Down

0 comments on commit 3a3f9e8

Please sign in to comment.