koa-zod-router
Advanced tools
Comparing version 1.0.1 to 1.0.2
# koa-zod-router | ||
## 1.0.2 | ||
### Patch Changes | ||
- 244e59a: Update Docs, fix transform type inference | ||
## 1.0.1 | ||
@@ -4,0 +10,0 @@ |
@@ -6,3 +6,3 @@ import * as koa from 'koa'; | ||
import bodyParser from 'koa-bodyparser'; | ||
import { ZodSchema, z } from 'zod'; | ||
import z, { ZodSchema, z as z$1 } from 'zod'; | ||
import * as formidable_PersistentFile from 'formidable/PersistentFile'; | ||
@@ -21,8 +21,8 @@ | ||
type ValidationOptions<Headers, Params, Query, Body, Files, Response> = { | ||
headers?: ZodSchema<Headers>; | ||
body?: ZodSchema<Body>; | ||
params?: ZodSchema<Params>; | ||
query?: ZodSchema<Query>; | ||
files?: ZodSchema<Files>; | ||
response?: ZodSchema<Response>; | ||
headers?: ZodSchema<Headers, z.ZodTypeDef, any>; | ||
body?: ZodSchema<Body, z.ZodTypeDef, any>; | ||
params?: ZodSchema<Params, z.ZodTypeDef, any>; | ||
query?: ZodSchema<Query, z.ZodTypeDef, any>; | ||
files?: ZodSchema<Files, z.ZodTypeDef, any>; | ||
response?: ZodSchema<Response, z.ZodTypeDef, any>; | ||
}; | ||
@@ -218,5 +218,5 @@ type ZodMiddleware<H, P, Q, B, F, R> = Middleware<DefaultState, ZodContext<H, P, Q, B, F>, R> | Middleware<DefaultState, ZodContext<H, P, Q, B, F>, R>[]; | ||
declare const zFile: () => z.ZodUnion<[z.ZodType<formidable_PersistentFile, z.ZodTypeDef, formidable_PersistentFile>, z.ZodType<formidable_PersistentFile, z.ZodTypeDef, formidable_PersistentFile>]>; | ||
declare const createRouteSpec: <Headers = z.ZodType<any, z.ZodTypeDef, any>, Params = z.ZodType<any, z.ZodTypeDef, any>, Query = z.ZodType<any, z.ZodTypeDef, any>, Body = z.ZodType<any, z.ZodTypeDef, any>, Files = z.ZodType<any, z.ZodTypeDef, any>, Response = z.ZodType<any, z.ZodTypeDef, any>>(spec: RouteSpec<Headers, Params, Query, Body, Files, Response>) => RouteSpec<Headers, Params, Query, Body, Files, Response>; | ||
declare const zFile: () => z$1.ZodUnion<[z$1.ZodType<formidable_PersistentFile, z$1.ZodTypeDef, formidable_PersistentFile>, z$1.ZodType<formidable_PersistentFile, z$1.ZodTypeDef, formidable_PersistentFile>]>; | ||
declare const createRouteSpec: <Headers = z$1.ZodTypeAny, Params = z$1.ZodTypeAny, Query = z$1.ZodTypeAny, Body = z$1.ZodTypeAny, Files = z$1.ZodTypeAny, Response = z$1.ZodTypeAny>(spec: RouteSpec<Headers, Params, Query, Body, Files, Response>) => RouteSpec<Headers, Params, Query, Body, Files, Response>; | ||
export { RouterOpts, ZodRouter, createRouteSpec, zodRouter as default, zFile }; |
{ | ||
"name": "koa-zod-router", | ||
"version": "1.0.1", | ||
"version": "1.0.2", | ||
"description": "", | ||
@@ -23,3 +23,4 @@ "main": "dist/index.js", | ||
"name": "Jake Fenley", | ||
"url": "https://github.com/jakefenley" | ||
"url": "https://github.com/jakefenley", | ||
"email": "jakefdev@gmail.com" | ||
}, | ||
@@ -26,0 +27,0 @@ "license": "MIT", |
112
README.md
@@ -10,2 +10,3 @@ # ⚡ koa-zod-router ⚡ | ||
[zod]: https://github.com/colinhacks/zod | ||
[coercion]: https://zod.dev/?id=coercion-for-primitives | ||
[koa-bodyparser]: https://github.com/koajs/bodyparser | ||
@@ -66,27 +67,10 @@ [formidable]: https://github.com/node-formidable/formidable | ||
### 🛠️ Options | ||
### Importing/Exporting routes | ||
| Param | Type | Description | | ||
| ---------- | ------------------- | ---------------------------------------------------------------------------------------- | | ||
| bodyParser | <code>Object</code> | koa-bodyparser [options](https://github.com/koajs/bodyparser#options) | | ||
| formidable | <code>Object</code> | formidable [options](https://github.com/node-formidable/formidable#options) | | ||
| koaRouter | <code>Object</code> | @koa/router [options](https://github.com/koajs/router/blob/master/API.md#new-routeropts) | | ||
| zodRouter | <code>Object</code> | koa-zod-router [options](#⚙️-zodrouter-options) | | ||
Most likely you'll want to seperate your routes into seperate files, and register them somewhere in your app's initialization phase. To do this you can use the helper function createRouteSpec and specify the route's properties. | ||
#### ⚙️ zodRouter options | ||
| Param | Type | Description | | ||
| -------------------- | -------------------- | --------------------------------------------------------- | | ||
| enableMultipart | <code>Boolean</code> | Enable Multipart parser middleware, used for file uploads | | ||
| exposeRequestErrors | <code>Boolean</code> | Send ZodErrors caused by client in response body | | ||
| exposeResponseErrors | <code>Boolean</code> | Send ZodErrors caused by the server in response body | | ||
### Import/Exporting routes | ||
Most likely you'll want to seperate your routes into seperate files, and register them somewhere else. To do this you can use the helper function createRouteSpec and specify the route's properties. | ||
`get-user.ts:` | ||
```js | ||
import { createRouteSpec } from '../src/util'; | ||
import { createRouteSpec } from 'koa-zod-router'; | ||
import { z } from 'zod'; | ||
@@ -114,18 +98,90 @@ | ||
```js | ||
import Koa from 'koa'; | ||
import zodRouter from 'koa-zod-router'; | ||
import { z } from 'zod'; | ||
import { getUserRoute } from './get-user.ts'; | ||
const app = new Koa(); | ||
const router = zodRouter(); | ||
router.register(getUserRoute); | ||
``` | ||
app.use(router.routes()); | ||
### Type coercion | ||
app.listen(3000, () => { | ||
console.log('app listening on http://localhost:3000'); | ||
When dealing with route parameters, query strings, and headers the incoming data will be parsed as strings to begin with. From a validation standpoint this can potentially be painful to deal with when dealing with things like `Date` in javascript. Luckily [zod] has a built in [coercion] method attached to its primitive data types to solve this! | ||
**convert a route parameter to a number:** | ||
```js | ||
router.register({ | ||
path: '/users/:id', | ||
method: 'get', | ||
handler: (ctx) => { | ||
console.log(typeof ctx.request.params.id); | ||
// 'number' | ||
}, | ||
validate: { | ||
params: z.object({ id: z.coerce.number() }), | ||
}, | ||
}); | ||
``` | ||
### Dealing with dates | ||
As mentioned above type coercion can be very useful in a lot of situations, especially when dealing with dates. Since `Date` cannot be passed directly into JSON we must convert both the data received and the data being sent back to the client. Avoid using `z.date()` in your schemas as these will result in validation errors. Instead use `z.coerce.date()` for input data, and `z.string()` (or your choice of primitive data-type) for output. | ||
```js | ||
router.register({ | ||
path: '/date', | ||
method: 'post', | ||
handler: (ctx) => { | ||
const { date } = ctx.request.body; | ||
console.log(date instanceof Date); | ||
// true | ||
ctx.body = { | ||
date: date.toISOString(), | ||
}; | ||
}, | ||
validate: { | ||
body: z.object({ date: z.coerce.date() }), // converts received string or number into date object | ||
response: z.object({ date: z.string() }), | ||
}, | ||
}); | ||
``` | ||
### Dealing with files | ||
koa-zod-router uses [formidable] for any requests received with the `Content-Type` header set to `multipart/*`. | ||
This functionality is disabled by default, to enable this functionality create an instance of zodRouter and pass in `{ zodRouter: { enableMultipart: true } }` as your config. Then to validate files utilize the helper function `zFile`. | ||
```js | ||
import zodRouter, { zFile } from 'koa-zod-router'; | ||
const fileRouter = zodRouter({ zodRouter: { enableMultipart: true } }); | ||
fileRouter.register({ | ||
path: '/uploads', | ||
method: 'post', | ||
handler: (ctx) => { | ||
const { file_one, multiple_files } = ctx.request.files; | ||
//... | ||
}, | ||
validate: { | ||
body: z.object({ hello: z.string() }), | ||
files: z.object({ | ||
file_one: zFile(), | ||
multiple_files: z.array(zFile()).or(zFile()), | ||
}), | ||
}, | ||
}); | ||
``` | ||
## API Reference | ||
[Reference](https://github.com/JakeFenley/koa-zod-router/tree/main/docs/API.md) | ||
## Feedback | ||
Found a bug? Have a question or idea? | ||
Please let me know in [Issues section](https://github.com/JakeFenley/koa-zod-router/issues). | ||
Found a vulnerability or other security issue? | ||
Please refer to [Security policy](https://github.com/JakeFenley/koa-zod-router/blob/main/SECURITY.md). |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
45658
184