Coder Social home page Coder Social logo

koa-router-zod-swagger's Introduction

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',
        },
      },
    },
  }),
);

koa-router-zod-swagger's People

Contributors

dependabot[bot] avatar vaso991 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

aqsous gewfy mrjono1

koa-router-zod-swagger's Issues

ResponseType Body should be optional?

Hey! thanks for the awesome lib. This is really useful.

I'm having an issue where I have to implement empty body responses on my endpoints.

Methods such as DELETE usually return a empty/null body. (Not an empty object)

Basically I just wanna save myself from having to write ctx.body = {} in those cases as I don't think it's necessary and having a hook that adds a empty object to all empty responses can have unaccounted side effects.

Can we make ResponseType .body optional?

ZodValidator not working if when you have other middleware added before ZodValidator

In the current setup if ZodValidator not the first middleware

What I recommend is to modify FindSchemaInStack function to be like this:

function FindSchemaInStack(
  stack: Router.Layer | Router.IMiddleware,
): ZodValidatorProps | undefined {
  if (Object.prototype.hasOwnProperty.call(stack, '_VALIDATOR_PROPS')) {
    // @ts-ignore
    return stack._VALIDATOR_PROPS as ZodValidatorProps;
  }
  if ('stack' in stack) {
    const zodStack = stack.stack.find(stackItem => Object.prototype.hasOwnProperty.call(stackItem, '_VALIDATOR_PROPS'))
    if (zodStack) {
      return FindSchemaInStack(zodStack);
    }
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.