-
Notifications
You must be signed in to change notification settings - Fork 191
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
sebastianwessel
wants to merge
4
commits into
honojs:main
Choose a base branch
from
sebastianwessel:feat/add_schema_validator_package
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+537
−1
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -45,4 +45,4 @@ | |
"tsup": "^7.2.0", | ||
"vitest": "^0.34.5" | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
# @hono/typeschema-validator | ||
|
||
## 1.0.0 | ||
|
||
### Major Changes |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
module.exports = require('../../jest.config.js') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", | ||
"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" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
}) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 andvitest
for testing, referring to thehello
middleware?https://github.com/honojs/middleware/tree/main/packages/hello