@easycrud/koa-router-crud
A koa-router extension for constructing CRUD router simply.

Table of Contents
Installation
npm install koa-router-crud
Feature
Transform the table definition schema into RESTful style CRUD routers of koa.
Basic example: the user.json will be transformed into the following routers:
GET /all_users[?username=xxx] get all users without pagination.
GET /users?page=1&pageSize=10[&username=xxx] get users with pagination.
GET /users/:id get a user by id.
POST /users create a user.
PUT /users/:id update a user by id.
DELETE /users/:id delete a user by id.
The first two routers can be appended query parameters to filter the result.
- fuzzy search:
column=value
- range search:
column=value1,value2 (column>=value1 and column<=value2)
Quick Start
import * as Koa from 'koa';
import * as Router from 'koa-router';
import * as Crud from '@easycrud/koa-router-crud';
const app = new Koa();
const router = new Router();
const crud = new Crud({
path: __dirname + '/../schemas',
dbConfig: {
client: 'mysql',
connection: {
host: '127.0.0.1',
port: 3306,
user: 'root',
password: '123456',
database: 'localdb',
timezone: '+08:00',
dateStrings: true,
},
},
}, router);
crud.build(app).then((router) => {
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
});
Main Dependencies
- koa - The application building framework.
- koa-router - The router construction base.
- koa-body - A request body parser middleware.
- knex.js - An SQL query builder to help operate databases.
- @easycrud/toolkits - Provide a Parser to output standard table model objects.
API Reference
Crud
Kind: Exported class
new Crud([opts], Router)
Create a new Crud instance. If Router is not provided, a new Router instance will be created.
Options
path (String) - directory or file path that pass to the Parser. The parsed table models will be stored in crud.tables.
tables (Array) - table models defined using standard table definition. If path is provided, tables will be ignored.
dbConfig (Object|Array) - knex configuration options that will be used for establishing database connections before the application start.
*If more than one dbConfig is provided, the value of dbConfig.database and [table].options.database must be guaranteed equal.
routerConfig (Object) - A configuration object with table name as key to customize the generated routers.
getUserAuth (Function) - (context: Router.RouterContext) => string A function to get the authorization value related to current user and the value is used for verifying row-level authorization.
koaBodyOptions (Object) - koa-body options that will be passed to koa-body middleware.
Customize routers
Set primary key
If the table does not have a primary key, it can be set manually.
const routerConfig = {
'user': {
'primaryKey': 'id',
}
}
Additionally, a composite primary key can be set as
const routerConfig = {
'user': {
'primaryKey': ['username', 'email'],
}
}
And the GET /users/:pk router will be changed to GET /users/row?username=:username&email=:email.
Custom router
The default corresponding handler methods to the routers are:
GET /all_[tablename] - all
GET /[tablename] - paginate
GET /tablename/:id - show
POST /tablename - store
PUT /tablename/:id - edit
DELETE /tablename/:id - destory
Change the default router like this:
const routerConfig = {
'user': {
'operates': {
'all': {
'method': 'get',
'path': '',
'middlewares': [],
'handler': (dao) => {
return async (ctx, next) => {
}
}
},
'auth': {
'method': 'get',
'path': 'auth',
'middlewares': [],
'handler': (dao) => {
return async (ctx, next) => {
}
}
}
}
}
}
Overwrite router
If the overwrite property is set to true, only the router defined in operates remain and the default router will be removed.
const routerConfig = {
'user': {
'overwrite': true,
'operates': {
}
}
}
crud.build(app) => Promise<Router>
Construct database connections and build the api routers, returning a Router instance.
crud.build(app).then((router) => {
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
});
Row-Level Authorization
const getUserAuth = (ctx) => {
return ctx.state.user.id;
}
Set rowAuth options of the table definition schema.
{
"options": {
"rowAuth": {
"column": "user_id",
"operates": ["read", "create", "update", "delete"]
}
}
}
Dao
dao.all(params) => Array|{err}
Get all records from the table.
- params: the query object get from
ctx.query used for filtering data.
dao.paginate(params) => Array|{err}
Get paginated records from the table.
dao.getByPk(pk, auth) => Object|{err}
Get a record by primary key.
- pk: the primary key-value pair.
{pkCol: pkVal}
- auth: the value of row authorization column.
{authCol: authVal}
dao.delByPk(pk, auth) => Object|{err}
Delete a record by primary key.
dao.create(data) => Object|{err}
Create a new record.
- data: the data to be created get from
ctx.request.body.data.
dao.updateByPk(pk, data, auth) => Object|{err}
Update a record by primary key.
- pk: the primary key-value pair.
{pkCol: pkVal}
- data: the data to be updated get from
ctx.request.body.data.
- auth: the value of row authorization column.
{authCol: authVal}
ctx.reply(data)
ctx.reply({ id: 1 });
ctx.reply({ err: { code: 404, message: 'not found' } });
Return the standard data.
{
"code": 0,
"msg": "success",
"data": {}
}