-
Notifications
You must be signed in to change notification settings - Fork 143
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
11 changed files
with
328 additions
and
0 deletions.
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,25 @@ | ||
name: ci-unknownutil-validator | ||
on: | ||
push: | ||
branches: [main] | ||
paths: | ||
- 'packages/unknownutil-validator/**' | ||
pull_request: | ||
branches: ['*'] | ||
paths: | ||
- 'packages/unknownutil-validator/**' | ||
|
||
jobs: | ||
ci: | ||
runs-on: ubuntu-latest | ||
defaults: | ||
run: | ||
working-directory: ./packages/unknownutil-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
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,2 @@ | ||
# @hono/unknownutil-validator | ||
|
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,46 @@ | ||
# Unknownutil validator middleware for Hono | ||
|
||
The type validator middleware using [Unknownutil](https://github.com/lambdalisue/deno-unknownutil) for [Hono](https://honojs.dev) applications. | ||
You can write a schema with unknownutil and check the type of the incoming values. | ||
|
||
## Usage | ||
|
||
```ts | ||
import { is } from 'unknownutil' | ||
import { uValidator } from '@hono/unknownutil-validator' | ||
|
||
const schema = is.ObjectOf({ | ||
name: is.String, | ||
age: is.Number, | ||
}) | ||
|
||
app.post('/author', uValidator('json', schema), (c) => { | ||
const data = c.req.valid('json') | ||
return c.json({ | ||
success: true, | ||
message: `${data.name} is ${data.age}`, | ||
}) | ||
}) | ||
``` | ||
|
||
Hook: | ||
|
||
```ts | ||
app.post( | ||
'/post', | ||
uValidator('json', schema, (result, c) => { | ||
if (result.error) { | ||
return c.text('Invalid!', 400) | ||
} | ||
}) | ||
//... | ||
) | ||
``` | ||
|
||
## Author | ||
|
||
Ryotaro "Justin" Kimura <https://github.com/ryoppippi> | ||
|
||
## 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,37 @@ | ||
{ | ||
"name": "@hono/unknownutil-validator", | ||
"version": "0.1.0", | ||
"description": "Validator middleware using unknonwnutil", | ||
"main": "dist/cjs/index.js", | ||
"module": "dist/esm/index.js", | ||
"types": "dist/esm/index.d.ts", | ||
"files": [ | ||
"dist" | ||
], | ||
"scripts": { | ||
"test": "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.*", | ||
"unknownutil": "^3.9.0" | ||
}, | ||
"devDependencies": { | ||
"hono": "^3.1.0", | ||
"unknownutil": "^3.9.0" | ||
} | ||
} |
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,60 @@ | ||
import type { Context, MiddlewareHandler, Env, ValidationTargets, TypedResponse } from 'hono' | ||
import { validator } from 'hono/validator' | ||
import { AssertError, ensure, type Predicate, type PredicateType } from 'unknownutil' | ||
|
||
export type Hook<T, E extends Env, P extends string> = ( | ||
result: { data: T; error: undefined } | { data: undefined; error: AssertError }, | ||
c: Context<E, P> | ||
) => Response | Promise<Response> | void | Promise<Response | void> | TypedResponse<T> | ||
|
||
export const uValidator = < | ||
T, | ||
S extends Predicate<T>, | ||
Target extends keyof ValidationTargets, | ||
E extends Env, | ||
P extends string, | ||
V extends { | ||
in: { [K in Target]: PredicateType<S> } | ||
out: { [K in Target]: PredicateType<S> } | ||
} = { | ||
in: { [K in Target]: PredicateType<S> } | ||
out: { [K in Target]: PredicateType<S> } | ||
} | ||
>( | ||
target: Target, | ||
schema: S, | ||
hook?: Hook<PredicateType<S>, E, P> | ||
): MiddlewareHandler<E, P, V> => | ||
validator(target, (value, c) => { | ||
let resultUnion: [AssertError, undefined] | [undefined, PredicateType<S>] | ||
|
||
try { | ||
resultUnion = [undefined, ensure(value, schema) as PredicateType<S>] | ||
} catch (error: unknown) { | ||
if (error instanceof AssertError) { | ||
resultUnion = [error, undefined] | ||
} else { | ||
throw new Error(undefined, { cause: error }) | ||
} | ||
} | ||
|
||
const [error, data] = resultUnion | ||
|
||
if (hook) { | ||
const hookResult = hook(error ? { data: undefined, error } : { data, error: undefined }, c) | ||
if (hookResult) { | ||
if (hookResult instanceof Response || hookResult instanceof Promise) { | ||
return hookResult | ||
} | ||
if ('response' in hookResult) { | ||
return hookResult.response | ||
} | ||
} | ||
} | ||
|
||
if (error) { | ||
return c.json({ success: false, error: error.message }, 400) | ||
} | ||
|
||
return value | ||
}) |
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,131 @@ | ||
import { Hono } from 'hono' | ||
import type { Equal, Expect } from 'hono/utils/types' | ||
import { is } from 'unknownutil' | ||
import { uValidator } from '../src' | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
type ExtractSchema<T> = T extends Hono<infer _, infer S> ? S : never | ||
|
||
describe('Basic', () => { | ||
const app = new Hono() | ||
|
||
const schema = is.ObjectOf({ | ||
name: is.String, | ||
age: is.Number, | ||
}) | ||
|
||
const route = app.post('/author', uValidator('json', schema), (c) => { | ||
const data = c.req.valid('json') | ||
return c.jsonT({ | ||
success: true, | ||
message: `${data.name} is ${data.age}`, | ||
}) | ||
}) | ||
|
||
type Actual = ExtractSchema<typeof route> | ||
type Expected = { | ||
'/author': { | ||
$post: { | ||
input: { | ||
json: { | ||
name: string | ||
age: number | ||
} | ||
} | ||
output: { | ||
success: true | ||
message: string | ||
} | ||
} | ||
} | ||
} | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
type verify = Expect<Equal<Expected, Actual>> | ||
|
||
it('Should return 200 response', async () => { | ||
const req = new Request('http://localhost/author', { | ||
body: JSON.stringify({ | ||
name: 'Superman', | ||
age: 20, | ||
}), | ||
method: 'POST', | ||
}) | ||
const res = await app.request(req) | ||
expect(res).not.toBeNull() | ||
expect(res.status).toBe(200) | ||
expect(await res.json()).toEqual({ | ||
success: true, | ||
message: 'Superman is 20', | ||
}) | ||
}) | ||
|
||
it('Should return 400 response', async () => { | ||
const req = new Request('http://localhost/author', { | ||
body: JSON.stringify({ | ||
name: 'Superman', | ||
age: '20', | ||
}), | ||
method: 'POST', | ||
}) | ||
const res = await app.request(req) | ||
expect(res).not.toBeNull() | ||
expect(res.status).toBe(400) | ||
const data = (await res.json()) as { success: boolean } | ||
expect(data['success']).toBe(false) | ||
}) | ||
}) | ||
|
||
describe('With Hook', () => { | ||
const app = new Hono() | ||
|
||
const schema = is.ObjectOf({ | ||
id: is.Number, | ||
title: is.String, | ||
}) | ||
|
||
app.post( | ||
'/post', | ||
uValidator('json', schema, (result, c) => { | ||
if (result.error) { | ||
return c.text('Invalid!', 400) | ||
} | ||
const data = result.data | ||
return c.text(`${data.id} is valid!`) | ||
}), | ||
(c) => { | ||
const data = c.req.valid('json') | ||
return c.json({ | ||
success: true, | ||
message: `${data.id} is ${data.title}`, | ||
}) | ||
} | ||
) | ||
|
||
it('Should return 200 response', async () => { | ||
const req = new Request('http://localhost/post', { | ||
body: JSON.stringify({ | ||
id: 123, | ||
title: 'Hello', | ||
}), | ||
method: 'POST', | ||
}) | ||
const res = await app.request(req) | ||
expect(res).not.toBeNull() | ||
expect(res.status).toBe(200) | ||
expect(await res.text()).toBe('123 is valid!') | ||
}) | ||
|
||
it('Should return 400 response', async () => { | ||
const req = new Request('http://localhost/post', { | ||
body: JSON.stringify({ | ||
id: '123', | ||
title: 'Hello', | ||
}), | ||
method: 'POST', | ||
}) | ||
const res = await app.request(req) | ||
expect(res).not.toBeNull() | ||
expect(res.status).toBe(400) | ||
}) | ||
}) |
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,8 @@ | ||
{ | ||
"extends": "./tsconfig.json", | ||
"compilerOptions": { | ||
"module": "CommonJS", | ||
"declaration": false, | ||
"outDir": "./dist/cjs" | ||
} | ||
} |
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,8 @@ | ||
{ | ||
"extends": "./tsconfig.json", | ||
"compilerOptions": { | ||
"module": "ESNext", | ||
"declaration": true, | ||
"outDir": "./dist/esm" | ||
} | ||
} |
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,9 @@ | ||
{ | ||
"extends": "../../tsconfig.json", | ||
"compilerOptions": { | ||
"rootDir": "./src", | ||
}, | ||
"include": [ | ||
"src/**/*.ts" | ||
], | ||
} |