/** module middleware2 Copyright (C) 2019.08 BraveWang */ 'use strict'; const MidCore = require('./midcore.js'); class Middleware extends MidCore { /** * 执行中间件,其中核心则是请求回调函数。 * @param {object} ctx 请求上下文实例。 */ async run(ctx) { try { //return await:把中间件链的返回值透传出去,同时保留 try/catch 捕获链上的异常。 //若写成 return this.exec(...),rejection 会绕过本层 catch。 return await this.exec(ctx, ctx.group); } catch (err) { //任一侧失败都不影响另一侧——否则 respond/end 抛错会跳过 errorHandle,链上错误永久丢失。 try { this.errorHandle(err, '--ERR-RESPONSE--'); } catch (e) { this.debug && console.error('--ERR-RESPONSE-handle--', e); } //此处失败不再上抛:调用方(http2 stream handler)不 await run(), //抛出会变成 unhandledRejection,而错误已经留痕,冒泡没有价值。 try { if (ctx.stream && !ctx.stream.destroyed && ctx.stream.writable) { if (!ctx.stream.headersSent) { ctx.stream.respond({ ':status' : '500' }); } ctx.stream.end(); } } catch (e) { this.debug && console.error('--ERR-RESPONSE-write--', e); } } } /** 这是最终添加的请求中间件。基于洋葱模型,这个中间件最先执行,所以最后会返回响应结果。 */ addFinal() { let fr = async (ctx, next) => { await next(ctx); if(!ctx.stream || ctx.stream.closed || ctx.stream.destroyed || !ctx.stream.writable) { return ; } let content_type = 'text/plain;charset=utf-8'; let datatype = typeof ctx.data; /** 如果还没有发送头部信息,则判断content-type类型,然后返回。 */ if (!ctx.stream.headersSent) { if (!ctx.dataHeaders['content-type']) { if (ctx.data instanceof Buffer || datatype === 'number') { ctx.dataHeaders['content-type'] = content_type; } else if (datatype === 'object') { ctx.dataHeaders['content-type'] = 'application/json;charset=utf-8'; } else if (datatype === 'string' && ctx.data.length > 1) { switch (ctx.data[0]) { case '{': case '[': content_type = 'application/json;charset=utf-8'; break; case '<': if (ctx.data[1] == '!') { content_type = 'text/html;charset=utf-8'; } break; default:; } ctx.setHeader('content-type', content_type); } } ctx.stream.respond(ctx.dataHeaders) } if (!ctx.data) { ctx.stream.end() } else if (ctx.data instanceof Buffer || datatype === 'string') { ctx.stream.end(ctx.data, ctx.dataEncoding) } else if (datatype === 'number') { ctx.stream.end(`${ctx.data}`) } else { ctx.stream.end(JSON.stringify(ctx.data)) } } this.add(fr) } } module.exports = Middleware;