Skip to content

Instantly share code, notes, and snippets.

@as3long
Last active January 22, 2019 02:16
Show Gist options
  • Save as3long/6d9b35228e09165a390b531a3e934aad to your computer and use it in GitHub Desktop.
Save as3long/6d9b35228e09165a390b531a3e934aad to your computer and use it in GitHub Desktop.
express自动路由
const express = require('express');
const path = require('path');
const trace = require('debug')(`app:${path.parse(__filename).base}`);
const controllers = require('./preRequire');
const router = express.Router();
// 实现自动路由
router.use('/', (req, res, next) => {
req.timeStart = Date.now();
const reqPath = req.path.replace('.html', '');
const pathArr = reqPath.split('/') || [];
const controller = pathArr[1] || 'index';
const action = pathArr[2] || 'index';
const args = pathArr.slice(3);
req.controller = controller;
req.action = action;
for (let i = 0; i < args.length; i += 1) {
args[i] = decodeURI(args[i]);
}
let hModule;
try {
const HClass = controllers[controller];
if (!HClass) {
trace('不存在的controller', controller);
next(new Error(`not found ${req.path}`));
return;
}
hModule = new HClass(req, res);
} catch (err) {
trace('自动路由错误', err);
next(err);
return;
}
let method;
if (req.method === 'POST') {
method = hModule[`${action}PostAction`];
} else if (req.method === 'PUT') {
method = hModule[`${action}PutAction`];
} else if (req.method === 'GET') {
method = hModule[`${action}Action`];
} else {
next();
return;
}
function doAction() {
return Promise.resolve(method.apply(hModule, args));
}
if (method) {
doAction().then((data) => {
if (data && !res.finished) {
res.send(data);
}
}).catch((err) => {
trace(`${controller}:${action}`, err);
next(err);
});
} else {
next();
}
});
module.exports = router;
function to(promise) {
return promise.then(data => [null, data]).catch(err => [err, null]);
}
class Base {
constructor(req, res) {
this.req = req;
this.res = res;
this.to = to;
}
outError(err, infoStr = '') {
const msg = err.response ? err.response.error.message : err.message;
this.res.json({
ret: -1,
msg
});
}
outJSON(data) {
this.res.json({
ret: 0,
msg: '',
data
});
}
}
module.exports = Base;
const requireDirectory = require('require-directory');
module.exports = requireDirectory(module, '../controller');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment