Skip to content

Get Swagger interface and input validate 😌Build Restful api in Koa like Hapijs

License

Notifications You must be signed in to change notification settings

haowen737/koa-swapi

Repository files navigation

koa-swapi

node npm GitHub last commit PRs Welcome Packagist

Super charged router for Koa

English | 中文

Koa-swapi is a user-friendly Koa middleware, design your koa router with koa-swapi like Hapijs, koa-swapi will validate each request components, and generate OpenAPI documant (fka Swagger RESTful API Documentation Specification).

Install

npm i koa-swapi --save

Usage Guide

Build Schema

const Joi = require('joi')
const { Route, Validator } = require('koa-swapi')

const catSchemas = [
  Route
    .get('/cat/:id')
    .tags(['catt', 'aninaml'])
    .summary('获得一只帅气猫')
    .description('想获得一只帅气猫的时候可以调用这个接口')
    .validate(
      Validator
        .params({
          id: Joi.string().required().min(2).max(4).description('猫的id')
        })
        .query({
          name: Joi.string().required().min(3).max(100).description('猫的名字'),
          sex: Joi.any().required().valid(['0', '1']).description('猫的性别, 0:男, 1:女')
        })
        .output({
          200: {
            body: Joi.string()
          }
        })
    )
    .create('getCat')
]

Build Controller

const controller = module.exports = {}

controller.getCat = async (ctx) => {
  ctx.status = 200;
  ctx.body = 'miaomiaomiao'
}

Build Api

const { Api } = require('koa-swapi')

const apis = [
  Api.schemas(catSchemas).handler(catController)
]

Register

// app.js
const Koa = require('koa')
const { Swapi } = require('koa-swapi')

const app = new Koa()
const swapi = new Swapi()

swapi.register(app, {
  basePath: '/api',
  // swagger: {...}: SwaggerSetting
  apis: apis,
  logger,// custom logger instance
  middleware,// custom middleware use before validate happens
})

app.listen(3333)

About

Get Swagger interface and input validate 😌Build Restful api in Koa like Hapijs

Resources

License

Stars

Watchers

Forks

Packages

No packages published