-
Notifications
You must be signed in to change notification settings - Fork 0
/
staticViewEndpoint.js
51 lines (46 loc) · 1.48 KB
/
staticViewEndpoint.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
var fs = require("fs");
var path = require("path");
var renderView = require("./renderView.js");
var previouslyRenderedStaticViews = {};
function staticViewEndpoint(view, viewModel) {
return function(req, res) {
var cachedResponse = previouslyRenderedStaticViews[view];
if(cachedResponse) {
return res.send(cachedResponse);
}
getStaticView(view, viewModel, (error, result) => {
if(error) {
console.error("Failed to render view " + view, error);
return res.fail(500);
}
previouslyRenderedStaticViews[view] = result;
res.send(result);
});
};
}
function getStaticView(view, viewModelPath, callback) {
if(!viewModelPath) {
return readAndRenderView(view, {}, callback);
}
fs.readFile(path.join(__dirname, viewModelPath), (error, buf) => {
if(error) {
return callback(error);
}
var viewModel = JSON.parse(buf.toString());
readAndRenderView(view, viewModel, callback);
})
}
function readAndRenderView(view, viewModel, callback) {
fs.readFile(path.join(__dirname, view), function(error, buf) {
if(error) {
return callback(error);
}
renderView(buf.toString(), viewModel, function(error, result) {
if(error) {
return callback(error);
}
callback(null, result);
});
});
}
module.exports = staticViewEndpoint;