npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

koa-route-schema

v0.0.3-0

Published

koa middleware to apply jsonschema with route

Downloads

2

Readme

koa-route-schema

koa middleware to apply jsonschema with route

Install

Install with npm

npm install koa-route-schema --save

or install using yarn

yarn add koa-route-schema

Features

  • built-in route handle, validate schema for each route stand-alone
  • work with other route system, support koa-better-route and koa-rest-route by default
  • add schema to each route handle separately
  • use ajv-errors, ajv-keywords easily, optionally
  • for same route

Usage

use schema validation globally

examples

trans schema list to schemaOptions and new KoaRouteSchema instance.

let routeschema = KoaRouteSchema({
  prefix: "v1",
  locale: 'en',
  schemaOptions: [
    {
      route: "/docs/:id",
      method: "GET",
      schema: {
        type: "object",
        properties: {
          type: {
            type: "string",
            title: "type",
            minLength: 0,
            maxLength: 5,
          },
        },
      },
    },
    {
      route: "/docs",
      method: "POST",
      schema: {
        type: "object",
        properties: {
          content: {
            type: "string",
            title: "content",
            minLength: 0,
            maxLength: 5000,
          },
          type: {
            type: "string",
            title: "type",
            mock: { mock: "@string" },
            minLength: 1,
            maxLength: 20,
            enum: ["example", "hexo", "weibo"],
          },
        },
        required: ["content", "type"],
      },
    },
  ],
});
// standalone mode
this.app.use(routeschema.middleware());
// attach mode
routeschema.attachToRouter(router /* router like koa-better-router */);

add schema to each route

examples

// schema.js

const RouteSchema = require('../../index')
const schema = new RouteSchema({
  prefix: 'v1'
})

module.exports = schema
// router.js

const compose = require('koa-compose')

const router = Router({ prefix: '/api' }).loadMethods()
router.schema = schema

router.get('/', compose([
  router.schema.routeQueryMiddleware({ type: 'object', properties: { type: { type: 'string', title: '类型', minLength: 1, maxLength: 20, enum: ['example', 'hexo', 'weibo'] } }, required: ['type'] }),
  (ctx, next) => {
    ctx.body = `Hello world! Prefix: ${ctx.query.type}`
    return next()
  }
]))

// can use generator middlewares
router.post('/foobar', compose([
  router.schema.routeBodyMiddleware({ type: 'object', properties: { content: { type: 'string', title: '内容', minLength: 0, maxLength: 5000 }, type: { type: 'string', title: '类型', mock: { mock: '@string' }, minLength: 1, maxLength: 20, enum: ['example', 'hexo', 'weibo'] } }, required: ['content', 'type'] }),
  function(ctx, next) {
    ctx.body = `Foo Bar Baz! ${ctx.request.body.content}`
    return next()
  }
]))

Options

var options = {
  prefix: 'v1',
  ajv: {},  // options passed to ajv constructor
  ajvErrors: undefined, // options directly pass to ajv-errors, you can also call ajv-errors to [instance].ajv
  ajvKeywords: undefined, // options directly pass to ajv-keywords, you can also call ajv-keywords to [instance].ajv
  locale: undefined, // local pass to ajv-i18n
  schemaOptions: []

  parseSchemaOptions: null,  // [function]-parse real schemaOptions
  getRoute: function(o) {   // [function]-get route from each schemaOption item
    return o.route
  },
  getMethod: function(o) {  // [function]-get method from each schemaOption item
    return o.method
  },
  getSchema: function(o) {  // [function]-get schema from each schemaOption item
    return o.schema
  },
  getBodySchema: null,  // [function]-get bodySchema from each schemaOption item
  getQuerySchema: null, // [function]-get querySchema from each schemaOption item

  getData: null,  // [function]-get data to validate from koa context

  attachRoute: null,  // [function]-attach middleware to router item, support koa-better-route and koa-rest-route by default

  bodyErrorPrefix: 'body: ',
  queryErrorPrefix: 'query: ',

  onError: null // [function]-handle validate error
}

API

KoaRouteSchema.prototype.loadSchemaOptions

load schema

KoaRouteSchema.prototype.middleware

get middleware globally, built-in route check, can work without other route system

KoaRouteSchema.prototype.attachToRouter

attach validate to appropriate route, accept one argument stand for router instance use options.attachRoute to define how to mix validation into supplied router system

KoaRouteSchema.prototype.routeMiddleware

get middleware used with route middleware, to validate supplied schema

KoaRouteSchema.prototype.routeBodyMiddleware

get middleware used with route middleware, to validate body schema

KoaRouteSchema.prototype.routeQueryMiddleware

get middleware used with route middleware, to validate query schema

Advanced

handle validate error

default handler is:

var defaultAjvOnError = function(err, ctx, errorsText) {
  if (err.message === 'RouteSchemaErrors') {
    ctx.throw(400, errorsText)
  } else {
    throw err
  }
}

var errorsText = _this.ajv.errorsText(validate.errors, { separator: '\n', dataVar: errorPrefix })

you can use custom handler by pass onError options.

new RouteSchema({
  onError: function (err, ctx, errorsText) {/* something */}
})

more validate information placed at ctx.routeSchemaErrors and ctx.routeSchemaValidate

ctx.routeSchemaErrors = validate.errors
ctx.routeSchemaValidate = validate