1.1.1 • Published 3 months ago

koa-router-zod-swagger v1.1.1

Weekly downloads
-
License
MIT
Repository
-
Last release
3 months ago

koa-router-zod-swagger

Validate router input and host swagger ui based on @koa/router and zod schema

Installation

$ npm install koa-router-zod-swagger

$ yarn add koa-router-zod-swagger

$ pnpm install koa-router-zod-swagger

Uses Zod, @koa/router And koa2-swagger-ui

Usage

Import Packages

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)

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

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 config as uiConfig)

router.get(
  '/docs',
  KoaRouterSwagger(router, {
    routePrefix: false,
    title: 'Test Api',
    swaggerOptions: {
      spec: {
        info: {
          version: '1.0.0',
          description: 'This is test api specs',
        },
      },
    },
  }),
);
1.1.1

3 months ago

1.0.19

10 months ago

1.1.0

10 months ago

1.0.18

10 months ago

1.0.17

11 months ago

1.0.16

12 months ago

1.0.20

10 months ago

1.0.15

12 months ago

1.0.14

12 months ago

1.0.13

1 year ago

1.0.12

1 year ago

1.0.11

1 year ago

1.0.10

1 year ago

1.0.9

1 year ago

1.0.8

1 year ago

1.0.7

1 year ago

1.0.6

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago