Skip to content

Commit

Permalink
Merge pull request #14 from JonathanBennett/refactor-2.0
Browse files Browse the repository at this point in the history
Refactor 2.0
  • Loading branch information
JonathanBennett authored Feb 22, 2018
2 parents 4c27954 + c1e8990 commit 80efba5
Show file tree
Hide file tree
Showing 5 changed files with 135 additions and 54 deletions.
19 changes: 19 additions & 0 deletions .jsbeautifyrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"js": {
"eol": "\n",
"preserve_newlines": true,
"max_preserve_newlines": 10,
"space_after_anon_function": true,
"brace_style": "collapse",
"keep_array_indentation": true,
"keep_function_indentation": false,
"space_before_conditional": true,
"break_chained_methods": false,
"eval_code": false,
"unescape_strings": false,
"wrap_line_length": 0,
"wrap_attributes": "auto",
"end_with_newline": true,
"comma_first": false
}
}
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ Configuration

By default it will connect to your Redis instance running on localhost and the default redis port with no authentication, and the default database number (normally 0). You can overwrite this by setting the `REDISTOGO_URL`, `REDISCLOUD_URL`, `REDISGREEN_URL` or `REDIS_URL` (in the format redis://user:password@host:port/databaseNumber). This currently covers all heroku add-ons for Redis to support quick start.

Acknowledgements
----------------

Thanks to the following for making branches with changes which were merged with the 0.2.0 release.
@nelsonkopliku
@eddietio

Todo
----

Expand Down
126 changes: 74 additions & 52 deletions lib/prerenderRedisCache.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,88 +3,110 @@
* redis_url (string) - Redis hostname (defaults to localhost)
* ttl (int) - TTL on keys set in redis (defaults to 1 day)
*/
var redis_url = process.env.REDISTOGO_URL || process.env.REDISCLOUD_URL || process.env.REDISGREEN_URL || process.env.REDIS_URL || "redis://127.0.0.1:6379",
url = require('url'),
ttl = process.env.PAGE_TTL || 86400;
var REDIS_URL = process.env.REDISTOGO_URL ||
process.env.REDISCLOUD_URL ||
process.env.REDISGREEN_URL ||
process.env.REDIS_URL ||
'redis://127.0.0.1:6379';

var url = require('url');
var TTL = process.env.PAGE_TTL || 86400;

// Parse out the connection vars from the env string.
var connection = url.parse(redis_url),
redis = require('redis'),
client = redis.createClient(connection.port, connection.hostname),
redis_online = false,
last_error = "",
last_end_message = ""; // Make redis connection
var connection = url.parse(REDIS_URL);
var redis = require('redis');
var client = redis.createClient(connection.port, connection.hostname);
var redisOnline = false;

var STATUS_CODES_TO_CACHE = {
200: true,
203: true,
204: true,
206: true,
300: true,
301: true,
404: true,
405: true,
410: true,
414: true,
501: true
};

// Make redis connection
// Select Redis database, parsed from the URL
connection.path = (connection.pathname || '/').slice(1);
connection.database = connection.path.length ? connection.path : '0';
client.select(connection.database);

// Parse out password from the connection string
if (connection.auth) {
client.auth(connection.auth.split(":")[1]);
client.auth(connection.auth.split(':')[1]);
}

// Catch all error handler. If redis breaks for any reason it will be reported here.
client.on("error", function (err) {
if(last_error === err.toString()) {
// Swallow the error for now
} else {
last_error = err.toString();
console.log("Redis Cache Error: " + err);
}
client.on('error', function (error) {
console.warn('Redis Cache Error: ' + error);
});
//
client.on("ready", function () {
redis_online = true;
console.log("Redis Cache Connected");

client.on('ready', function () {
redisOnline = true;
console.log('Redis Cache Connected');
});

client.on("end", function (err) {
if(err) {
err = err.toString();
if(last_end_message == err) {
// Swallow the error for now
} else {
last_end_message = err;
redis_online = false;
console.log("Redis Cache Conncetion Closed. Will now bypass redis until it's back.");
}
}
client.on('end', function () {
redisOnline = false;
console.warn(
'Redis Cache Conncetion Closed. Will now bypass redis until it\'s back.'
);
});

module.exports = {
beforePhantomRequest: function (req, res, next) {
//
if (req.method !== 'GET' || redis_online !== true) {
requestReceived: function (req, res, next) {
//
if (req.method !== 'GET' || !redisOnline) {
return next();
}

client.get(req.prerender.url, function (err, result) {
// Page found - return to prerender and 200
if (!err && result) {
res.send(200, result);
client.get(req.prerender.url, function (error, result) {
if (!error && result) {
var response = JSON.parse(result);
var headers = response.headers;
var key;

for (key in headers) {
if (headers.hasOwnProperty(key)) {
res.setHeader(key, headers[key]);
}
}
res.send(response.statusCode, response.content);
} else {
next();
}
});
},

afterPhantomRequest: function (req, res, next) {
if (redis_online !== true) {
pageLoaded: function (req, res, next) {
if (!redisOnline || !STATUS_CODES_TO_CACHE[req.prerender.statusCode]) {
return next();
}
// Don't cache anything that didn't result in a 200. This is to stop caching of 3xx/4xx/5xx status codes
if (req.prerender.statusCode === 200) {
client.set(req.prerender.url, req.prerender.documentHTML, function (err, reply) {
// If library set to cache set an expiry on the key.
if (!err && reply && ttl && ttl != 0) {
client.expire(req.prerender.url, ttl, function (err, didSetExpiry) {
console.warn(!!didSetExpiry);
});
}
});
}

var key = req.prerender.url;
var response = {
statusCode: req.prerender.statusCode,
content: req.prerender.content.toString(),
headers: req.prerender.headers
};
client.set(key, JSON.stringify(response), function (error, reply) {
// If library set to cache set an expiry on the key.
if (!error && reply && TTL) {
client.expire(key, TTL, function (error, didSetExpiry) {
if (!error && !didSetExpiry) {
console.warn('Could not set expiry for "' + key + '"');
}
});
}
});

next();
}
};
33 changes: 33 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "prerender-redis-cache",
"version": "0.1.3",
"version": "0.2.0",
"description": "Prerender plugin for Redis caching",
"main": "index.js",
"scripts": {
Expand All @@ -22,6 +22,6 @@
},
"homepage": "https://github.com/jonathanbennett/prerender-redis-cache",
"dependencies": {
"redis": "~0.10.1"
"redis": "^2.8.0"
}
}

0 comments on commit 80efba5

Please sign in to comment.