@yhiot/utils
Version:
105 lines (97 loc) • 2.77 kB
JavaScript
/**
* Koa-Router的中间件,预处理restful-url的参数.
* 处理如下格式URL:
// router.get('/user', getUsers);
// router.get('/user/:_id', getUser);
// router.put('/user/:_id', updateUser);
// router.delete('/user/:_id', removeUser);
// router.post('/user', createUser);
* GET类型分两种:
+ 有_id的表示获取单个
+ 无_id表示查询多个
* PUT类型只有一种: 更新单个
* POST类型只有一种: 创建单个
* DELETE类型只有一种: 删除单个
*/
import Errcode, { EC } from '../Errcode';
import { memParse as parseQueryString } from '@yhiot/dbcached';
export function preRestfulCreator(prefix) {
if (!prefix) prefix = '';
return async function preRestful(ctx, next) {
let path = ctx.path;
if (!path.startsWith(prefix)) {
// 非prefix开头,不用处理.
return await next();
}
let subpath = path.substring(prefix.length);
let fields = subpath.split('/') || [];
let method = ctx.method;
switch (method) {
case 'GET': {
let _id = fields[1];
let qstr = ctx.request.querystring;
if (qstr) {
qstr = decodeURIComponent(qstr);
}
if (qstr && qstr.startsWith('?')) {
qstr = qstr.substr(1);
}
let options = parseQueryString(qstr);
if (!_id) {
// 无_id表示查列表
ctx.state._type = 'retrieve';
} else {
ctx.state._type = 'get';
}
ctx.state._id = _id;
ctx.state._options = options;
break;
}
case 'POST': {
let args = ctx.request.body;
if (!args) {
throw new Errcode('error! args is null', EC.ERR_PARAM_ERROR);
}
ctx.state._type = 'create';
ctx.state._args = args;
break;
}
case 'PUT': {
let _id = fields[1];
let args = ctx.request.body;
if (!_id) {
throw new Errcode('error! _id is null', EC.ERR_PARAM_ERROR);
}
if (!args) {
throw new Errcode('error! args is null', EC.ERR_PARAM_ERROR);
}
ctx.state._type = 'update';
ctx.state._id = _id;
ctx.state._args = args;
break;
}
case 'DELETE': {
let _id = fields[1];
if (!_id) {
throw new Errcode('error! _id is null', EC.ERR_PARAM_ERROR);
}
ctx.state._type = 'remove';
ctx.state._id = _id;
break;
}
default:
ctx.state._type = 'none';
break;
}
return await next();
};
}
export function postRestfulCreator(restfulFunction) {
return async function restfulResult(ctx) {
let result = await restfulFunction(ctx.state);
ctx.body = {
errcode: 0,
result,
};
};
}