Skip to content
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

feat: add @hono/schema-validator middleware #370

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
6 changes: 6 additions & 0 deletions .changeset/cyan-penguins-bathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@hono/schema-validator': major
---

Add @hono/schema-validator middleware.
This middleware leverages [TypeSchema](https://typeschema.com), offering an abstraction layer that facilitates interaction with a variety of validation libraries through a unified interface. Consequently, there is no immediate requirement to develop a dedicated middleware for each validation library. This not only reduces maintenance efforts but also extends support to validation libraries that may currently lack compatibility.
25 changes: 25 additions & 0 deletions .github/workflows/ci-schema-validator.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: ci-schema-validator
on:
push:
branches: [main]
paths:
- 'packages/schema-validator/**'
pull_request:
branches: ['*']
paths:
- 'packages/schema-validator/**'

jobs:
ci:
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./packages/schema-validator
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 18.x
- run: yarn install --frozen-lockfile
- run: yarn build
- run: yarn test
2 changes: 1 addition & 1 deletion packages/swagger-editor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,4 @@
"tsup": "^7.2.0",
"vitest": "^0.34.5"
}
}
}
5 changes: 5 additions & 0 deletions packages/typeschema-validator/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# @hono/typeschema-validator

## 1.0.0

### Major Changes
56 changes: 56 additions & 0 deletions packages/typeschema-validator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Universal validator middleware for Hono

The validator middleware using [TypeSchema](https://typeschema.com) for [Hono](https://honojs.dev) applications.
You can write a schema with various schema libraries and validate the incoming values.

The preferred validation library must be additionally installed.
The list of supported validation libraries can be found at [TypeSchema](https://typeschema.com/#coverage).

## Usage

```ts
import { z } from 'zod'
import { schemaValidator, type ValidationError } from '@hono/typeschema-validator'

const schema = z.object({
name: z.string(),
age: z.number(),
})

app.post('/author', schemaValidator('json', schema), (c) => {
const data = c.req.valid('json')
return c.json({
success: true,
message: `${data.name} is ${data.age}`,
})
})

app.onError(async (err, c) => {
if (err instanceof ValidationError) {
return c.json(err, err.status)
}
return c.text('Internal Server Error', 500)
})
```

Hook:

```ts
app.post(
'/post',
schemaValidator('json', schema, (result, c) => {
if (!result.success) {
return c.text('Invalid!', 400)
}
})
//...
)
```

## Author

Sebastian Wessel <https://github.com/sebastianwessel>

## License

MIT
1 change: 1 addition & 0 deletions packages/typeschema-validator/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('../../jest.config.js')
43 changes: 43 additions & 0 deletions packages/typeschema-validator/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"name": "@hono/schema-validator",
"version": "0.0.0",
"description": "Validator middleware for multiple schema validation libraries based on schema.com",
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"types": "dist/esm/index.d.ts",
"files": [
"dist"
],
"scripts": {
"test": "NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\" jest",
"build:cjs": "tsc -p tsconfig.cjs.json",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you use tsup to build and vitest for testing, referring to the hello middleware?

https://github.com/honojs/middleware/tree/main/packages/hello

"build:esm": "tsc -p tsconfig.esm.json",
"build": "rimraf dist && yarn build:cjs && yarn build:esm",
"prerelease": "yarn build && yarn test",
"release": "yarn publish"
},
"license": "MIT",
"publishConfig": {
"registry": "https://registry.npmjs.org",
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/honojs/middleware.git"
},
"homepage": "https://github.com/honojs/middleware",
"peerDependencies": {
"hono": ">=3.9.0"
},
"dependencies": {
"@typeschema/main": "^0.14.1"
},
"devDependencies": {
"@typeschema/zod": "^0.14.0",
"hono": "^3.11.7",
"jest": "^29.7.0",
"rimraf": "^5.0.5",
"typescript": "^5.3.3",
"zod": "3.19.1"
}
}
92 changes: 92 additions & 0 deletions packages/typeschema-validator/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import type { Infer, InferIn, Schema } from '@typeschema/main'
import type {ValidationIssue} from '@typeschema/core'
import { validate } from '@typeschema/main'
import type { Context, Env, MiddlewareHandler, TypedResponse, ValidationTargets } from 'hono'
import { HTTPException } from 'hono/http-exception'
import { validator } from 'hono/validator'

export type Hook<T, E extends Env, P extends string, O = {}> = (
result:
| { success: true; data: T; inputData: unknown }
| { success: false; issues: Array<ValidationIssue>; inputData: unknown },
c: Context<E, P>,
) => Response | Promise<Response> | void | Promise<Response | void> | TypedResponse<O>

type HasUndefined<T> = undefined extends T ? true : false


type HTTPExceptionOptions = {
res?: Response;
message?: string;
data?:unknown
};

export class ValidationError extends HTTPException {

private data:unknown
constructor(
options?: HTTPExceptionOptions,
) {
/* Calling the constructor of the parent class (Error) and passing the message. */
super(400,options)
this.data=options?.data
Error.captureStackTrace(this, this.constructor)

Object.setPrototypeOf(this, ValidationError.prototype)
this.name = this.constructor.name
}

getData(){
return this.data
}

toJSON(){
return {
status: this.status,
message: this.message,
data: this.data
}
}
}

export const schemaValidator = <
T extends Schema,
Target extends keyof ValidationTargets,
E extends Env,
P extends string,
I = InferIn<T>,
O = Infer<T>,
V extends {
in: HasUndefined<I> extends true ? { [K in Target]?: I } : { [K in Target]: I }
out: { [K in Target]: O }
} = {
in: HasUndefined<I> extends true ? { [K in Target]?: I } : { [K in Target]: I }
out: { [K in Target]: O }
},
>(
target: Target,
schema: T,
hook?: Hook<Infer<T>, E, P>,
): MiddlewareHandler<E, P, V> =>
validator(target, async (value, c) => {
const result = await validate(schema, value)

if (hook) {
const hookResult = hook({ inputData: value, ...result }, c)
if (hookResult) {
if (hookResult instanceof Response || hookResult instanceof Promise) {
return hookResult
}
if ('response' in hookResult) {
return hookResult.response
}
}
}

if (!result.success) {
throw new ValidationError({ message: 'Custom error message',data:{issues:result.issues,target} })
}

const data = result.data as Infer<T>
return data
})
Loading