yapi/server/middleware/mockServer.js

66 lines
2.1 KiB
JavaScript
Raw Normal View History

2017-07-10 20:02:44 +08:00
import yapi from '../yapi.js';
import projectModel from '../models/project.js'
import interfaceModel from '../models/interface.js'
import Mock from 'mockjs'
module.exports = async (ctx, next) => {
2017-07-26 15:31:16 +08:00
yapi.commons.log('Server Recevie Request...')
let hostname = ctx.hostname;
2017-07-10 20:02:44 +08:00
let config = yapi.WEBCONFIG;
2017-07-11 12:12:43 +08:00
if(ctx.hostname === config.webhost){
2017-07-10 20:02:44 +08:00
if(next) await next();
return true;
}
2017-07-26 15:31:16 +08:00
yapi.commons.log('MockServer Running...')
2017-07-10 20:02:44 +08:00
let projectInst = yapi.getInst(projectModel), projects;
try{
projects = await projectInst.getByDomain(hostname);
}catch(e){
return ctx.body = yapi.commons.resReturn(null, 403, e.message);
}
2017-07-26 15:31:16 +08:00
let matchProject = [], maxBasepath = 0;
2017-07-10 20:02:44 +08:00
for(let i=0, l = projects.length; i< l; i++){
let project = projects[i];
2017-07-26 15:31:16 +08:00
if(ctx.path && ctx.path.indexOf(project.basepath) === 0){
2017-07-17 15:51:15 +08:00
matchProject.push(project);
if(project.basepath.length > maxBasepath){
maxBasepath = project.basepath.length;
matchProject = project;
}
2017-07-10 20:02:44 +08:00
}
}
2017-07-17 15:51:15 +08:00
if(matchProject === false){
2017-07-10 20:02:44 +08:00
return ctx.body = yapi.commons.resReturn(null, 400, '不存在的domain');
}
2017-07-17 15:51:15 +08:00
let project = matchProject, interfaceData;
2017-07-10 20:02:44 +08:00
let interfaceInst = yapi.getInst(interfaceModel);
try{
interfaceData = await interfaceInst.getByPath(project._id, ctx.path.substr(project.basepath.length));
if(!interfaceData || interfaceData.length === 0){
return ctx.body = yapi.commons.resReturn(null, 404, '不存在的api');
}
if(interfaceData.length > 1){
return ctx.body = yapi.commons.resReturn(null, 405, '存在多个api请检查数据库');
}
interfaceData = interfaceData[0];
if(interfaceData.res_body_type === 'json'){
return ctx.body = Mock.mock(
yapi.commons.json_parse(interfaceData.res_body)
);
}
return ctx.body = interfaceData.res_body;
}catch(e){
return ctx.body = yapi.commons.resReturn(null, 409, e.message);
}
}