fkc
Version:
FKC application service framework.
93 lines • 3.15 kB
JavaScript
;
module.exports = (obj)=>{
const {host} = obj;
const use = require('./use');
const files = require('../use/files');
const errs = require('../json/error');
const ctxUse = require('../use/ctx');
const stream = require('../use/stream');
const {error,getData,getUrl,file} = require('../util');
return async (req,res)=>{
let ctx;
let arg;
let path;
let def = [];
if(host['*']){
arg = host['*'];
}else{
let web = req.headers.host.split(':')[0];
if(obj.reg) {
for (let k = 0;k < obj.reg.length;k++) {
if(obj.reg[k].test(web)) web = obj.reg[k];
};
}
if(host[web]) arg = host[web];
}
if(!arg) {
error(res,errs.host[1]);
return;
}
ctx = ctxUse(req,res);
if(arg.arg){
for (const key in arg.arg) {
ctx.arg[key] = arg.arg[key](req,res);
}
}
const urls = req.url.split('?');
ctx.req.path = urls[0];
const md = ctx.req.method;
if(urls[1]) ctx.req.data = getUrl(urls[1]);
if(arg.use) def = def.concat(arg.use);
if(arg.path['*']){
path = arg.path['*'];
if(path.all) def = def.concat(path.all.code);
if(path[md]) def = def.concat(path[md].code);
}
let url = urls[0];
if(arg.reg){
for (let i = 0;i < arg.reg.length;i++) {
if(arg.reg[i].test(url)) url = arg.reg[i];//匹配正则路由
};
}
path = arg.path[url];
if(path){
if(path.all) {
if(path.all.reg) ctx.req.data = {...getData(path.all.reg,urls[0]),...ctx.req.data};
def = def.concat(path.all.code);
}
if(path[md]) {
if(path[md].reg) ctx.req.data = {...getData(path[md].reg,urls[0]),...ctx.req.data};
def = def.concat(path[md].code);
}
ctx = await use(req,res,ctx,def);
if(ctx){
if(ctx===1) {
error(res,errs.stop);
return;
}
if(path.file){
if(path.file.data){
file(res,path.file);
return;
}
if(path.file.url){
stream(req,res,path.file);
return;
}
if(path.file.dir){
files(req,res,{url,path:urls[0],file:path.file});
return;
}
}
if(path[md]) {
error(res,errs.out);
} else {
error(res,errs.method);
}
}
}else{
if(await use(req,res,ctx,def)) error(res,errs.router[2]);
return;
}
}
}