Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/vaso991/koa-router-zod-swagger
Koa2 validator and swagger generator.
https://github.com/vaso991/koa-router-zod-swagger
koa koa-router koa2 openapi swagger validation zod
Last synced: 5 days ago
JSON representation
Koa2 validator and swagger generator.
- Host: GitHub
- URL: https://github.com/vaso991/koa-router-zod-swagger
- Owner: vaso991
- Created: 2023-01-29T15:48:23.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2024-09-30T17:27:18.000Z (about 1 month ago)
- Last Synced: 2024-10-31T08:52:18.994Z (12 days ago)
- Topics: koa, koa-router, koa2, openapi, swagger, validation, zod
- Language: TypeScript
- Homepage:
- Size: 196 KB
- Stars: 10
- Watchers: 1
- Forks: 3
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# koa-router-zod-swagger
> Validate router input and host swagger ui based on @koa/router and zod schema
## Installation
```sh
$ npm install koa-router-zod-swagger$ yarn add koa-router-zod-swagger
$ pnpm install koa-router-zod-swagger
```
> Uses [`Zod`](https://github.com/colinhacks/zod), [`@koa/router`](https://github.com/koajs/router) And [`koa2-swagger-ui`](https://github.com/scttcper/koa2-swagger-ui)## Usage
### Import Packages
```js
import Koa from 'koa';
import KoaRouter from 'koa-router';
import { z } from 'zod';
import { ZodValidator, ZodValidatorProps, KoaRouterSwagger } from 'koa-router-zod-swagger';
const app = new Koa();
const router = new KoaRouter();
```### Create validation Zod object schema ([See Zod Documentation](https://github.com/colinhacks/zod#readme))
```js
const RouterSchema: ZodValidatorProps = {
summary: 'Make test post request',
description: `Make [API](https://en.wikipedia.org/wiki/API) Request`,
query: z.object({
queryParam: z.string(),
}),
body: z.object({
bodyParamString: z.string(),
bodyParamNumber: z.number(),
}),
files: {
file1: true,
multipleFiles: {
multiple: true
},
optionalFile: {
optional: true
}
},
filesValidator: z.object({
file1: z.object({ // formidable.File object
size: z.number().min(5 * 1000).max(7 * 1000), // Min 5KB, Max 7KB.
mimetype: z.enum(['image/png'])
})
}),
params: z.object({
param1: z.string(),
}),
header: z.object({
'user-agent': z.string()
}),
response: {
description: 'Response returned successfully',
validate: true,
body: z.object({
query: z.object(),
params: z.object(),
body: z.object()
})
}
};
```
### Validate
```js
router.post('/api/:param1', ZodValidator(RouterSchema), (ctx) => {
ctx.body = {
query: ctx.request.query,
params: ctx.params,
body: ctx.request.body,
};
});
```### Serve Swagger Docs (pass [koa2-swagger-ui](https://github.com/scttcper/koa2-swagger-ui#config) config as `uiConfig`)
```js
router.get(
'/docs',
KoaRouterSwagger(router, {
routePrefix: false,
title: 'Test Api',
swaggerOptions: {
spec: {
info: {
version: '1.0.0',
description: 'This is test api specs',
},
},
},
}),
);
```