-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtaunus-hapi.js
122 lines (97 loc) · 3.02 KB
/
taunus-hapi.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
'use strict';
var util = require('util');
var pkg = require('./package.json');
var matcher = /\{([a-z]+)(\?)?\}/ig;
function factory (taunus) {
var plugin = {
register: register
};
function register (plugin, options, next) {
if (taunus.resolve) {
taunus.resolve.use(matcher);
}
taunus.mount(addRoute, options);
next();
function addRoute (d) {
plugin.route({
method: 'GET',
path: d.route,
config: d.config,
handler: handler
});
function handler (request, reply) {
if (d.actionFn) {
d.actionFn(request, response);
} else {
response({});
}
function response (vm) {
var headers = {};
var statusCode;
var req = request;
var res = {
set: set,
status: status,
send: send,
json: json,
jsonp: jsonp
};
req.url = req.url.path;
function get (name) {
return headers[name.toLowerCase()];
}
function set (name, value) {
headers[name.toLowerCase()] = value;
}
function status (code) {
statusCode = code;
}
function send (data) {
respond(data);
}
function json (data) {
respond(data);
}
function jsonp (data) {
var cb = req.query.callback;
var body = JSON.stringify(data);
if (!(get('Content-Type'))) {
set('Content-Type', 'application/json');
}
if (typeof cb === 'string' && cb.length !== 0) {
set('Content-Type', 'text/javascript');
set('X-Content-Type-Options', 'nosniff');
// restrict callback charset
cb = cb.replace(/[^\[\]\w$.]/g, '');
// replace chars not allowed in JavaScript that are in JSON
body = body
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
// the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"
// the typeof check is just to reduce client error noise
body = util.format('/**/ typeof %s === \'function\' && %s(%s);', cb, cb, JSON.stringify(data));
}
respond(body);
}
function respond (response) {
var r = reply(response).code(statusCode || 200);
Object.keys(headers).forEach(function add (key) {
r.header(key, headers[key]);
});
}
taunus.render(d, vm, req, res, next);
}
function next (err) {
if (err) {
console.warn('Taunus called .next(err), won\'t reply.\n', err.stack || err.message || err);
} else {
console.info('Taunus called .next(), won\'t reply.');
}
}
}
}
}
plugin.register.attributes = { pkg: pkg };
return plugin;
}
module.exports = factory;