UNPKG

mm_os

Version:

这是超级美眉服务端框架,用于快速构建应用程序。

81 lines (78 loc) 1.99 kB
/** * 调用函数 * @param {Object} ret 设置响应结果 * @param {Object} res 响应器 * @param {String} t 请求类型 * @return {String} 处理后的响应结果 */ function render_body(ret, res, t) { var type; if (res.type) { type = res.type; } var tp = typeof(ret); if (tp === "object") { if (!type) { /// 设置响应头 if (t.indexOf('xml') !== -1) { type = t; } else { type = "application/json; charset=utf-8"; } res.type = type; } else { if (type.indexOf('json') !== -1) { type = "application/json; charset=utf-8"; } else if (type.indexOf('html') !== -1) { type = "text/html"; } else if (type.indexOf('xml') !== -1) { type = "text/xml; charset=utf-8"; } else { type = "text/plain; charset=utf-8"; } res.type = type; } if (type.indexOf('/xml') !== -1) { return $.toXml(ret); } else { return JSON.stringify(ret); } } else if (tp === "string") { ret = ret.trim(); if (!type) { if (ret.startWith('{') && ret.endWith('}')) { res.type = "application/json; charset=utf-8"; } else if (ret.startWith('[') && ret.endWith(']')) { res.type = "application/json; charset=utf-8"; } else if (ret.endWith("</html>")) { res.type = "text/html"; } else { res.type = "text/plain; charset=utf-8"; } } } return ret; }; /** * web渲染 * @param {Object} server 服务 * @param {Object} config 配置参数 */ module.exports = function(server, config) { // 使用路由(主要) server.use(async (ctx, next) => { if (ctx.path !== "/favicon.ico") { await $.eventer.run('web_render', ctx, ctx.db); var event = $.event_admin('api'); var ret = await event.render(ctx.path, ctx, ctx.db); if (!ctx.body && ret) { ctx.body = ret; } if (ctx.body) { ctx.body = render_body(ctx.body, ctx.response, ctx.request.type); } } await next(); }); return server; };