-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
85 lines (81 loc) · 3.09 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
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
var buildTags = function(links) {
var tags = "";
for (var i in links) {
var link = links[i];
var platform = link.platform;
tags += '\n<meta property="al:' + platform + '">\n';
var keys = Object.keys(link);
for (var j in keys) {
var key = keys[j];
if (key !== "platform") {
tags += '<meta property="al:' + platform + ":" + key + '" content="' + link[key] + '">\n';
}
}
}
return tags;
};
var injectMetaOptions = function(str, options) {
return str.replace(/<head>((?:.|\n|\r)+?)<\/head>/i, "<head>$1" + buildTags(options)+"</head>");
};
var _ = require("underscore");
module.exports = function(platforms) {
return function(req, res, next) {
var apps = platforms;
if (_.isFunction(platforms)) {
apps = platforms(req, res);
}
if (!_.isArray(apps)) {
apps = [ apps ];
}
var htmlMetaHeaders = req.headers["prefer-html-meta-tags"] || "";
var preferAppLinks = _.some(htmlMetaHeaders.split(","), function(value) {
return value.trim() === "al";
});
if (preferAppLinks) {
// Always returns html
res.set("Content-Type", "text/html");
}
// Only modify the render function once in case app links
// is defined multiple times
if (!res._appLinks) {
var render = res.render;
res.render = function(view, options, finishCallback) {
options = options || {};
// Support callback function as second arg
if (_.isFunction(options)) {
finishCallback = options, options = {};
}
var self = this;
var defaultCallback = function(err, str) {
if (err) {
return req.next(err);
}
self.send(str);
};
if (!_.isFunction(finishCallback)) {
finishCallback = defaultCallback;
}
if (res._appLinks.preferAppLinks) {
// If we prefer App Links, let's render simple HTML
str = "<html><head></head><body></body><html>";
str = injectMetaOptions(str, res._appLinks.meta);
res.send(str);
} else {
render.call(res, view, options, function(err, str) {
str = injectMetaOptions(str, res._appLinks.meta);
// remove _appLinks object from response
delete res._appLinks;
finishCallback(err, str);
});
}
};
}
// Inject app links meta to response object
res._appLinks = res._appLinks || {};
res._appLinks.meta = res._appLinks.meta || [];
// Render more specific meta tag first
res._appLinks.meta = apps.concat(res._appLinks.meta);
res._appLinks.preferAppLinks = preferAppLinks;
next();
};
};