Coder Social home page Coder Social logo

koa-scheme's Introduction

koa-scheme

koa-scheme is a parameter validation middleware for koa.

version v3.0.0 support for koa2

Install

npm i koa-scheme --save

Usage

scheme(config, options)
  • config: {Object|String} scheme object or path.
  • options: {Object}
    • debug: {Boolean} If true, print compiled config and throw error, Default false.

app.js

var koa = require('koa');
//var bodyParser = require('koa-bodyparser');
var scheme = require('koa-scheme');
var conf = require('./scheme');
var route = require('./route');

var app = koa();
//app.use(bodyParser());
app.use(scheme(conf));

route(app);

app.listen(3000, function() {
  console.log("listening on 3000")
});

scheme.json

{
  "/(.*)": {
    "request": {
      "header": {
        "version": "[1-9]+"        
      }
    }
  },
  "/": {
    "response": {
      "status": 200
    }
  },
  "GET /user/:username": {
    "response": {
      "body": {
        "name": /[a-z]+/i,
        "age": "[0-9]{1,3}"
      }
    }
  },
  "/user/:username": {
    "request": {
      "method": "(POST|patch)",
      "body": {
        "name": "[a-zA-Z]+",
        "age": /[0-9]{1,3}/
      }
    },
    "response": {
      "status": 200
    }
  },
  "(delete|OPTIONS) /user/:username": {
    ...
  }
}

see path-to-regexp.

NB: when use body-parser middleware (like: koa-bodyparser) before koa-scheme, you could configure 'body' field in 'request'.

use function:

scheme.js

module.exports = {
  "/users": {
    "request": {
      "method": "POST",
      "body": {
        "nameArr": testRequestNameArr
      }
    }
  }
}

function testRequestNameArr(arr) {
  if (arr.length === 3 && arr[1] === 'nswbmw') {
    return true;
  } else {
    return false;
  }
}

with validator:

scheme.js

var validator = require('validator');

module.exports = {
  "GET /user/:username": {
    "response": {
      "body": {
        "age": validator.isNumeric,
        "email": validator.isEmail,
        "webset": validator.isURL,
        ...
      }
    }
  }
}

Even you could write flat object like this:

{
  "GET /user/:username": {
    "response": {
      "body.age": validator.isNumeric,
      "body.email": validator.isEmail,
      "body.family.mother.age": validator.isNumeric
    }
  }
}

Example

scheme.js

var validator = require('validator');

module.exports = {
  "/(.*)": {
    "request": {
      "header.version": "[1-9]+"
    }
  },
  "/users": {
    "request": {
      "method": "GET"
    },
    "response": {
      "body": testRes
    }
  },
  "GET /user/:username": {
    "response": {
      "body": {
        "name": "[a-zA-Z]+",
        "age": validator.isNumeric,
        "email": validator.isEmail
      }
    }
  },
  "/user/:username": {
    "request": {
      "method": "(POST|PATCH)",
      "body.name": /[a-zA-Z]+/,
      "body.age": "[0-9]{1,3}",
      "body.email": validator.isEmail
    }
  },
  "(delete|OPTIONS) /user/:username": {
    "response": {
      "status": 200
    }
  }
}

// throw a error is ok
function testRes(arr) {
  throw new Error('badRequest');
}

Test

npm test

License

MIT

koa-scheme's People

Contributors

note520 avatar nswbmw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

koa-scheme's Issues

Example of differing method schemas

This looks like exactly what I'm looking for, and I've got it quickly up and running validating incoming requests.

I'm uncertain about something, though. Say I have an /api/session endpoint. POSTing should require login/password parameters, but DELETE requires none and logs out. How do I model this? It looks like API endpoints are keyed first on path, then on request/response. Seems like it'd make sense to key on path, then method, then request/response. But perhaps I'm missing something.

Can't validate request params?

I have a GET request like /apis/users/:userId/base?gender=0. I want to validate the params : userId 、gender and so on. How can i do this?

remove try catch

Hi,

I recommend removing the whole try-catch statements, and let all errors throw, then someone could use the uniform interface:

app.use(function *(next) {
  try {
    yield next;
  } catch (err) {
    this.status = err.status || 500;
    this.body = err.message;
    this.app.emit('error', err, this);
  }
}));

also, we simply our source code and reduce the number of lines, too.
otherwise dude :)

/cc @nswbmw

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.