UNPKG

floodesh-lib

Version:

core library for floodesh, which contains core request, response and context class, also used for flowesh

110 lines (93 loc) 2.42 kB
'use strict'; const Mof = require('mof') const Emitter = require('events') //const merge = require('utils-merge') const Context = require('./context.js') const request = require('./request.js') const response = require('./response.js') /* * depart into 3 stags, onrequest, onresponse, onparsed * get task * normalize task(could use a middleware) * send to other middleware * * events raised by `Core`: `resquest`, `response`,`process` * events subscribed by `Core`: `responding`, `parsed` * * */ module.exports = class Core extends Emitter{ constructor() { super(); this.middleware = new Mof(); } /** * normalize a request options. (keep it simple) * * @reqopt String or Object of options * @api private * */ // _normalize(reqopt){ // let opt = { // gzip:true, // encoding:null // }; // if(typeof reqopt === 'string') return (opt.uri=reqopt && opt); // if(typeof reqopt === 'object') return merge(opt,reqopt); // throw new TypeError("request options must be a string or an object."); // } /** * delegate `use` function of Mof **/ use(fn){ this.middleware.use(fn); return this; } /** * enqueue jobs. * * @opt `options` of request * @theTime callback of bottleneck when it's time * * @api protected */ enqueue(opt){ let self = this; let ctx = this._createContext(opt); process.nextTick(()=>{ this.middleware.callback(ctx => self.emit('complete',ctx), (err, ctx) => self.emit('error', err,ctx ) )( ctx ); }); return ctx; } /** * Initialize a new context. * * @api private */ _createContext(task){ const ctx = Context(); const rq = ctx.request = Object.create(request); const rs = ctx.response = Object.create(response); ctx.opt = task//this._normalize(task); ctx.request.req = ctx.response.res = null; rq.ctx = rs.ctx = ctx; ctx.app = rq.app = rs.app = this; ctx.meta = new Map(); ctx.dataSet = new Map(); ctx.tasks = []; ctx.resourceList = Object.create(null); // ctx.performance = { // enqueueTimestamp:enqueueTimestamp, // bottleneckTimestamp:Date.now(), // requestTimestamp:null, // responseTimestamp:null, // responsemwTimestamp:null, // parsedTimestamp:null // }; return ctx; } toJSON(){ return ""; } }