-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
49 lines (43 loc) · 1.72 KB
/
index.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
// Middleware that injects the shared data and sharify script
module.exports = function(req, res, next) {
// Clone the "constant" sharify data for the request so
// request-level data isn't shared across the server potentially
// exposing sensitive data.
var data = {};
for(var key in module.exports.data) {
data[key] = module.exports.data[key];
};
// Inject a sharify object into locals for `= sharify.data` and `= sharify.script()`
res.locals.sharify = {
data: data,
script: function() {
return '<script type="text/javascript">' +
'window.__sharifyData = ' +
//There are tricky rules about safely embedding JSON within HTML
//see http://stackoverflow.com/a/4180424/266795
JSON.stringify(data)
.replace(/</g, '\\u003c')
.replace(/-->/g, '--\\>')
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029') +
';</script>';
}
};
// Alias the sharify short-hand for convience
res.locals.sd = res.locals.sharify.data;
next();
};
// The shared hash of data
module.exports.data = {};
// When required on the client via browserify, run this snippet that reads the
// sharify.script data and injects it into this module.
var bootstrapOnClient = module.exports.bootstrapOnClient = function() {
if (typeof window != 'undefined' && window.__sharifyData) {
module.exports.data = window.__sharifyData;
// Conveniently expose globals so client-side templates can access
// the `sd` and `sharify.data` just like the server.
if (!window.sharify) window.sharify = module.exports;
if (!window.sd) window.sd = window.__sharifyData;
}
};
bootstrapOnClient();