UNPKG

wns-http-package

Version:

HTTP package/bundle for WNS Middleware

128 lines (110 loc) 2.65 kB
/** * WNS's HTTP Package * @copyright © 2013- Pedro Nasser ® * @license: MIT * @page http://github.com/pedronasser/wns-http-package */ /** * @class wnsHttpResponse * @classdesc Class with all methods to be attached to the ServerResponse object * @author Pedro Nasser */ var _ = require('lodash'); var Buffer = require('buffer').Buffer; module.exports = { /** * Methods */ methods: { /** * Return the controller url */ getUrl: function () { return this.request.url; }, /** * Error Access Handler * @param {number} code - http status code * @param {string} [msg] - http status msg * @param {boolean} [fatal] - fatal error? means no redirect */ errorHandler: function (code,msg,fatal) { var self = this; this.statusCode=code || 500; this.err.push([code,msg]); delete this.info.headers['Content-type']; this.send(); }, /** * Redirect the request to an address. * @param {string} url * @param {boolean} [terminate] * @param {number} [statusCode] */ redirect: function () { var self = this; if (self.finished) return false; self.debug('REDIRECTING request to: '+_.toArray(arguments).join(', '),1); var url; var terminate; var statusCode; if (typeof arguments[0]=='number') { url = arguments[1]+'' || '/'; statusCode=arguments[0]; terminate = new Boolean(arguments[2]).valueOf() || false; } else { url=arguments[0]+'' || '/'; statusCode = 303; terminate = new Boolean(arguments[1]).valueOf() || false; } this.statusCode = statusCode; this.setHeader('Location', url || '/'); if (terminate) this.end(); }, /** * Alias for ServerResponse.end(); */ write: function (data) { this.writeOutput.apply(this,arguments) this._write.apply(this,arguments); }, /** * Alias for ServerResponse.end(); */ end: function (data) { this.writeOutput.apply(this,arguments) if (this.data.length == 0) this.data = new Buffer(''); else if (this.data.length == 1) this.data = this.data.shift(); else this.data = Buffer.concat(this.data); this.emit('send'); this._end.apply(this,arguments); }, /** * Write and end. */ send: function () { this.write.apply(this,arguments); this.end(); }, writeOutput: function (data) { if (Buffer.isBuffer(data)) this.data.push(data); else if (_.isString(data)) { data = new Buffer(data); this.data.push(data); } } } };