-
Notifications
You must be signed in to change notification settings - Fork 6
/
fetch.js
87 lines (72 loc) · 2.34 KB
/
fetch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const _defaultsDeep = require('lodash/defaultsDeep');
const EmberCliDeployError = require('./errors/ember-cli-deploy-error');
const ioRedis = require('ioredis');
const memoize = require('memoizee');
let redisClient;
const defaultConnectionInfo = {
host: "127.0.0.1",
port: 6379
};
const _defaultOpts = {
revisionQueryParam: 'index_key',
memoize: false,
memoizeOpts: {
maxAge: 5000, // ms
preFetch: true,
max: 4, // a sane default (current pointer, current html and two indexkeys in cache)
}
};
let opts;
function _getOpts(opts) {
opts = opts || {};
return _defaultsDeep({}, opts, _defaultOpts);
}
let initialized = false;
function _initialize(connectionInfo, passedOpts) {
opts = _getOpts(passedOpts);
let config = connectionInfo ? connectionInfo : defaultConnectionInfo;
redisClient = new ioRedis(config);
if (opts.memoize === true) {
let memoizeOpts = opts.memoizeOpts;
memoizeOpts.async = false; // this should never be overwritten by the consumer
memoizeOpts.length = 1;
redisClient.get = memoize(redisClient.get, memoizeOpts);
}
initialized = true;
}
function fetchIndex(req, keyPrefix, connectionInfo, passedOpts) {
if (!initialized) {
_initialize(connectionInfo, passedOpts);
}
let indexkey;
if (req.query[opts.revisionQueryParam]) {
let queryKey = req.query[opts.revisionQueryParam].replace(/[^A-Za-z0-9]/g, '');
indexkey = `${keyPrefix}:${queryKey}`;
}
let customIndexKeyWasSpecified = !!indexkey;
function retrieveIndexKey(){
if (indexkey) {
return Promise.resolve(indexkey);
} else {
return redisClient.get(keyPrefix + ":current").then(function(result){
if (!result) { throw new Error(); }
return keyPrefix + ":" + result;
}).catch(function(){
throw new EmberCliDeployError("There's no " + keyPrefix + ":current revision. The site is down.", true);
});
}
}
return retrieveIndexKey().then(function(indexkey){
return redisClient.get(indexkey);
}).then(function(indexHtml){
if (!indexHtml) { throw new Error(); }
return indexHtml;
}).catch(function(err){
if (err.name === 'EmberCliDeployError') {
throw err;
} else {
throw new EmberCliDeployError("There's no " + indexkey + " revision. The site is down.", !customIndexKeyWasSpecified);
}
});
}
module.exports = fetchIndex;