Skip to content
This repository has been archived by the owner on Mar 8, 2023. It is now read-only.

Commit

Permalink
plugins/cookies: rewrite as class
Browse files Browse the repository at this point in the history
  • Loading branch information
skenqbx committed Apr 22, 2015
1 parent 9ccda3c commit 6d00ca7
Showing 1 changed file with 30 additions and 22 deletions.
52 changes: 30 additions & 22 deletions lib/plugins/cookies.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down Expand Up @@ -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 = [];
Expand Down Expand Up @@ -116,4 +124,4 @@ function set(jar, options) {
if (cookies.length > 0) {
options.request.headers.Cookie = cookies.join('; ');
}
}
};

0 comments on commit 6d00ca7

Please sign in to comment.