Gathering detailed insights and metrics for koa-zod-rest
Gathering detailed insights and metrics for koa-zod-rest
npm install koa-zod-rest
Typescript
Module System
Node Version
NPM Version
62.1
Supply Chain
91.8
Quality
85.8
Maintenance
100
Vulnerability
98.2
License
TypeScript (86.52%)
JavaScript (11.73%)
Shell (1.76%)
Total Downloads
345
Last Day
2
Last Week
8
Last Month
345
Last Year
345
1 Stars
7 Commits
1 Watching
2 Branches
2 Contributors
Minified
Minified + Gzipped
Latest Version
1.0.0-rc2
Package Id
koa-zod-rest@1.0.0-rc2
Unpacked Size
37.78 kB
Size
10.00 kB
File Count
47
NPM Version
10.2.3
Node Version
20.10.0
Publised On
11 Jan 2025
Cumulative downloads
Total Downloads
Last day
0%
2
Compared to previous day
Last week
-20%
8
Compared to previous week
Last month
0%
345
Compared to previous month
Last year
0%
345
Compared to previous year
This document was automatically generated using OpenAI's o1 model.
A library that simplifies RESTful API development in Koa.js using Zod and OpenAPI, automating request/response validation and Swagger documentation generation.
koa-zod-rest
is a library that assists in Koa applications by leveraging Zod schemas to validate requests and responses, and automatically generates Swagger documentation according to the OpenAPI specification. This allows for easy type safety and documentation handling during API development.
1# dependencies 2npm install koa @koa/router zod @anatine/zod-openapi koa2-swagger-ui 3 4# devDependencies 5npm install -D typescript @types/node @types/koa @types/koa__router openapi3-ts
Finally,
1npm install koa-zod-rest
Let's introduce how to use koa-zod-rest
through a simple example.
1import Koa from 'koa'; 2import Router from '@koa/router'; 3import { z } from 'zod'; 4import { rest } from 'koa-zod-rest'; 5import { koaSwagger } from 'koa2-swagger-ui'; 6 7const app = new Koa(); 8const router = new Router(); 9 10// Create OpenAPI document object 11const swaggerObject = { 12 openapi: '3.0.0', 13 info: { 14 title: 'API Documentation', 15 version: '1.0.0', 16 }, 17 paths: {}, 18}; 19 20// Define request schema 21const getUserParamsSchema = z.object({ 22 id: z.string().uuid(), 23}); 24 25// Define response schema 26const userResponseSchema = z.object({ 27 id: z.string().uuid(), 28 name: z.string(), 29 email: z.string().email(), 30}); 31 32rest( 33 router, 34 'get', 35 '/users/{id}', 36 { 37 request: { 38 params: getUserParamsSchema, // then, `ctx.data.params` right after, it will be infered as `{ id: string; }` 39 }, 40 response: { 41 status: 200, 42 schema: userResponseSchema, // then, `ctx.body` right after, it will be infered as `{ id: string; name: string; email: string }` 43 }, 44 swagger: { 45 swaggerObject, 46 auto: { 47 summary: 'Retrieve User Information', 48 tags: ['User'], 49 }, 50 }, 51 }, 52 async (ctx) => { 53 // Logic to fetch user information (example) 54 // In this handler, Just use koa's approach that you already know with `ctx.data` 55 const { id } = ctx.data.params; // << This `ctx.data` will be inferred that you declared in `request.params` before 56 57 // ...And, `ctx.body` must be one of `undefined` or `{id: string; ...}` that you declared in `response.schema` before. 58 ctx.body = { 59 id, 60 name: 'Hong Gil-dong', 61 email: 'hong@example.com', 62 }; 63 }, 64); 65 66// Swagger UI Setup 67app.use( 68 koaSwagger({ 69 routePrefix: '/path-to-swagger', 70 swaggerOptions: { 71 spec: { ...swaggerObject }, 72 }, 73 }), 74); 75 76// Apply router and middleware 77app.use(router.routes()).use(router.allowedMethods()); 78 79app.listen(3000, () => { 80 console.log('Server is running on port 3000'); 81});
After running the server, you can verify the automatically generated Swagger documentation by accessing http://localhost:3000/path-to-swagger.
koa-zod-rest
provides the following main features:
rest(router, method, path, routeConfig, ...handlers)
Defines a RESTful API route, handling request/response validation and Swagger documentation generation.
router
: An instance of @koa/router
's Routermethod
: HTTP method ('get'
, 'post'
, 'put'
, 'delete'
, 'patch'
)path
: API path (in Path-to-RegExp format)routeConfig
: Route configuration object(Check out below details)...handlers
: Koa middleware handlersrouteConfig
Objectrequest
: Configuration for the request
headers
: Zod schema for request headers (AnyZodObject | undefined
)params
: Zod schema for URL parameters (AnyZodObject | undefined
)query
: Zod schema for query parameters (AnyZodObject | undefined
)body
: Zod schema for request body (AnyZodObject | undefined
)response
: Configuration for the response
status
: HTTP status code (number
, default: 200
)schema
: Zod schema for response body (AnyZodObject | undefined
)headers
: Response headers (Record<string, string>
, optional)validation
: Whether to validate the response (boolean
, default: false
)middlewares
: Middleware settings
useBefore
: Array of middlewares to execute before the handler (Middleware[]
, optional)useAfter
: Array of middlewares to execute after the handler (Middleware[]
, optional)swagger
: Settings for Swagger documentation
swaggerObject
: OpenAPI document object (OpenAPIObject
)auto
: Automatically generated Swagger settings (OperationObject
, optional)
tags
: Tags (string | string[]
, optional)custom
: Custom Swagger settings(override) (OperationObject
, optional)hidden
: Whether to hide this route from the Swagger documentation (boolean
, default: false
)koa-zod-rest
throws the following errors when request or response validation fails:
class InvalidRequestError extends Error {}
: When request validation failsclass InvalidResponseError extends Error {}
: When response validation failsYou can handle these errors in your application to return appropriate responses. For example:
1app.use(async (ctx, next) => { 2 try { 3 await next(); 4 } catch (error) { 5 if (error instanceof InvalidRequestError) { 6 ctx.status = 400; 7 ctx.body = { 8 message: error.message, 9 errors: error.zodErrors.errors, 10 }; 11 } else if (error instanceof InvalidResponseError) { 12 ctx.status = 500; 13 ctx.body = { 14 message: error.message, 15 errors: error.zodErrors.errors, 16 }; 17 } else { 18 ctx.status = 500; 19 ctx.body = { 20 message: 'Internal Server Error', 21 }; 22 } 23 } 24});
koa-zod-rest
will not interfere with Koa's pure context. So, if you want to implement your business logic using Koa's standard methods, feel free to proceed as you already know how.
ctx.req.headers
contains all the basic headers that you might need.ctx.request.body
may contain multipart/form-data content. If so, please use other plugins or packages such as multer
. and use it.Distributed under the MIT License.
This project will not be actively maintained. So if you want to use an improved or new feature, feel free to fork or download the original source code and modify it.
No vulnerabilities found.
No security vulnerabilities found.