@easycrud/koa-router-crud v1.0.3
@easycrud/koa-router-crud
A koa-router extension for constructing CRUD router simply.
Table of Contents
Installation
npm install koa-router-crudFeature
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/:idget a user by id.POST /userscreate a user.PUT /users/:idupdate a user by id.DELETE /users/:iddelete 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 incrud.tables.tables (Array)- table models defined using standard table definition. Ifpathis provided,tableswill be ignored.dbConfig (Object|Array)- knex configuration options that will be used for establishing database connections before the application start.
*If more than onedbConfigis provided, the value ofdbConfig.databaseand[table].options.databasemust be guaranteed equal.routerConfig (Object)- A configuration object with table name as key to customize the generated routers.getUserAuth (Function)-(context: Router.RouterContext) => stringA 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 tokoa-bodymiddleware.
Customize routers
Set primary key
If the table does not have a primary key, it can be set manually.
const routerConfig = {
// customize the router for the table `user`
'user': {
'primaryKey': 'id',
}
}Additionally, a composite primary key can be set as
const routerConfig = {
// customize the router for the table `user`
'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]-allGET /[tablename]-paginateGET /tablename/:id-showPOST /tablename-storePUT /tablename/:id-editDELETE /tablename/:id-destory
Change the default router like this:
const routerConfig = {
// customize the router for the table `user`
'user': {
'operates': {
// Change the default router, 'all|paginate|show|store|edit|destory'
'all': {
// set the http method, 'get|post|put|delete|patch'
'method': 'get',
// change the default path
'path': '',
// add some middlewares before the handler
'middlewares': [],
// change the default handler
'handler': (dao) => {
// The parameter `dao` is a `Dao` instance. It provide some help functions to operate the database.
return async (ctx, next) => {
// do something
}
}
},
// Add a new router
'auth': {
'method': 'get',
'path': 'auth',
'middlewares': [],
'handler': (dao) => {
return async (ctx, next) => {
// do something
}
}
}
}
}
}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 = {
// customize the router for the table `user`
'user': {
'overwrite': true,
'operates': {
// ...
}
}
}Construct database connections and build the api routers, returning a Router instance.
crud.build(app).then((router) => {
// Register the router and start the application
// after the databases are connected and the routers are built.
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
});Row-Level Authorization
const getUserAuth = (ctx) => {
// Get the authorization value related to current user
return ctx.state.user.id;
}Set rowAuth options of the table definition schema.
{
//...
"options": {
"rowAuth": {
"column": "user_id",
// Operations that require authorization.
"operates": ["read", "create", "update", "delete"]
}
}
}Dao
Get all records from the table.
- params: the query object get from
ctx.queryused for filtering data.
Get paginated records from the table.
Get a record by primary key.
- pk: the primary key-value pair.
{pkCol: pkVal} - auth: the value of row authorization column.
{authCol: authVal}
Delete a record by primary key.
Create a new record.
- data: the data to be created get from
ctx.request.body.data.
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": {}
}