kane-internal-router
v0.5.1
Published
Koa middleware to create API routes and validate user inputs
Downloads
1
Readme
Kane Internal Router
Koa middleware that uses koa-router and Joi to validate user inputs.
Requirements
You need to execute node
version 8
at least (async
/await
).
Installation
# npm
npm install --save kane-internal-router
# yarn
yarn add kane-internal-router
Usage
Calling the package will return a koa router with a new method that handles routes with Joi schemas for validation. By default unknown keys are allowed.
You can validate headers, body and params of a request. If Joi does not return a validation error, the code in the handler will be executed.
const Koa = require("koa");
const {Joi, KaneRouter} = require("kane-internal-router");
// by default, the router will:
// - limit the body size to 10MB
// - set a prefix (i.e. "/v2")
// - allow unknown routes and parameters to be invoked (it will however ignore them)
const router = new KaneRouter();
// you can freely add new routes to the router
// the structure is unique as below
const routeConfig = [
{
method: "patch",
path: "/users/:id",
// see the API for more details:
// https://github.com/hapijs/joi/blob/v14.0.1/API.md
validate: {
params: {
id: Joi.string().uuid({version: ["uuidv4"]}).required()
},
query: {
where: Joi.string().allow("")
},
header: {
authorization: Joi.string().required()
},
body: {
email: Joi.string().min(6).max(254).lowercase().email(),
// use email as username if it's empty
username: Joi.string().min(3).max(254).lowercase().regex(/^[A-Za-z0-9.]+$/, "username"),
}
},
// the handler param can also be an array of Koa middlewares
handler: (ctx, next) => {/* stuff */}
}
];
router.add(routeConfig);
const app = new Koa();
const routes = router.middleware();
app.use(routes);
app.listen();
The router also exposes a static method to determine if the request can be handled:
const Koa = require("koa");
const {KaneRouter} = require("kane-internal-router");
const app = new Koa();
const router = new KaneRouter();
const routeConfig = [/* config */];
const catchAllRoute = {
method: "all",
path: "(.*)",
handler: (ctx) => {
const matched = KaneRouter.match(routeConfig, ctx.method, ctx.path);
if (matched) {
// stuff
}
}
};
router.add(routeConfig);
router.add(catchAllRoute);
app
.use(router.middleware())
.listen();
Linting
Made using eslint
. To enforce rules to be applied, use yarn lint:fix
.
Testing
Simply invoke yarn test
.
Contributing
First, install the dependencies using yarn
:
yarn install --frozen-lockfile
Verify that your project is configured correctly by launching tests:
yarn test
Before you start coding make sure that you've read our CONTRIBUTING
guide!