diff --git a/lib/plugins/cookies.js b/lib/plugins/cookies.js index 521f431..39b2f61 100644 --- a/lib/plugins/cookies.js +++ b/lib/plugins/cookies.js @@ -2,35 +2,46 @@ var net = require('net'); -function cookiesPlugin(rail, opt_options) { - opt_options = opt_options || {}; - var pluginOptions = { - jar: opt_options || {} - }; +function CookiesPlugin(rail, options) { + if (!(this instanceof CookiesPlugin)) { + return new CookiesPlugin(rail, options); + } + this._rail = rail; + + this.jar = options.jar || {}; + + this._setup(); +} +module.exports = CookiesPlugin; + + +CookiesPlugin.prototype._setup = function() { + var self = this; + var rail = this._rail; - // after configure() rail.on('plugin-configure', function(call, options) { - set(pluginOptions.jar, options); + if (options.cookies !== false) { + self._setHeader(options); + } }); - // on response rail.on('plugin-response', function(call, options, response) { - parse(pluginOptions.jar, options, response); + if (options.cookies !== false) { + self._parseHeaders(options, response); + } }); - - return pluginOptions; -} -module.exports = cookiesPlugin; +}; -function parse(jar, options, response) { +CookiesPlugin.prototype._parseHeaders = function(options, response) { var i, j, p; var tokens, cookie; var domain = options.request.host; var cookies = response.headers['set-cookie']; + var jar = this.jar; - if (!cookies || options.cookies === false) { + if (!cookies) { return; } @@ -67,19 +78,16 @@ function parse(jar, options, response) { jar[domain][cookie.name] = cookie; response.cookies[cookie.name] = cookie; } -} +}; -function set(jar, options) { +CookiesPlugin.prototype._setHeader = function(options) { var domain = options.request.host; var cookies = []; var i, keys, tokens; var now = Date.now(); var expired = 0; - - if (options.cookies === false) { - return; - } + var jar = this.jar; if (net.isIP(domain) > 0) { tokens = []; @@ -116,4 +124,4 @@ function set(jar, options) { if (cookies.length > 0) { options.request.headers.Cookie = cookies.join('; '); } -} +};