/
journey.js
436 lines (380 loc) · 15.1 KB
/
journey.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
var path = require('path');
require.paths.unshift(path.join(__dirname, 'vendor'),
path.join(__dirname, 'journey'));
var sys = require("sys"),
http = require("http"),
events = require('events'),
fs = require("fs"),
url = require('url');
var querystring = require('querystring');
// Escape RegExp characters in a string
var escapeRe = (function () {
var specials = '. * + ? | ( ) [ ] { } \\ ^ ? ! = : $'.split(' ').join('|\\');
var re = new(RegExp)('(\\' + specials + ')', 'g');
return function (str) {
return (typeof(str) === 'string') ? str.replace(re, '\\$1') : str;
};
})();
var journey = exports;
var BadRequest = function (msg) {
this.status = 400;
this.headers = {};
this.body = { error: msg };
};
var NotFound = function (msg) {
this.status = 404;
this.headers = {};
this.body = { error: msg };
};
var MethodNotAllowed = function (allowed) {
this.status = 405;
this.headers = { allow: allowed };
this.body = { error: "method not allowed." };
};
var NotAcceptable = function (accept) {
this.status = 406;
this.headers = {};
this.body = {
error: "cannot generate '" + accept + "' response",
only: "application/json"
};
};
var NotImplemented = function (msg) {
this.status = 501;
this.headers = {};
this.body = { error: msg };
};
journey.env = 'development';
journey.version = [0, 2, 8];
//
// The Router
//
journey.Router = function Router(routes, options) {
var map = journey.map(this);
map.__defineGetter__('root', function () {
return this.get('/');
});
map.__defineGetter__('any', function () {
return this.route(/(.*)/);
});
this.routes = [];
this.options = options || {};
// Call map() in the context of `this.map`, so `this`
// can be used instead of the passed argument.
routes.call(map, map);
};
journey.Router.methods = ['GET', 'PUT', 'POST', 'DELETE', 'HEAD'];
journey.map = function (context) {
return {
paths: [],
get: function (pattern, opts) { return this.route('GET', pattern, opts) },
put: function (pattern, opts) { return this.route('PUT', pattern, opts) },
post: function (pattern, opts) { return this.route('POST', pattern, opts) },
del: function (pattern, opts) { return this.route('DELETE', pattern, opts) },
route: function (/* variable arguments */) {
var route, args = Array.prototype.slice.call(arguments).filter(function (a) { return a }),
// Defaults
pattern = this.paths.length ? '' : /.*/,
ignoreCase = false,
method = journey.Router.methods,
constraints = {};
args.forEach(function (arg) {
if (journey.Router.methods.indexOf(arg) !== -1 || Array.isArray(arg)) {
method = arg;
} else if (typeof(arg) === "object") {
constraints = arg;
} else if (typeof(arg) === "string" || arg.exec) {
pattern = arg;
} else {
throw new(Error)("cannot understand route.");
}
});
if (typeof(pattern) === "string") {
pattern = escapeRe(pattern);
} else {
// If we're in a nested path, '/i' doesn't mean much,
// as we concatinate strings and regexps.
ignoreCase = this.paths.length || pattern.ignoreCase;
pattern = pattern.source;
}
// Trim trailing and duplicate slashes and add ^$ markers
pattern = '^' + this.paths.concat(pattern ? [pattern] : [])
.join('/')
.match(/^\^?(.*?)\$?$/)[1] // Strip ^ and $
.replace(/^(\/|\\\/)(?!$)/, '') // Strip root / if pattern != '/'
.replace(/(\/|\\\/)+/g, '/') + '$'; // Squeeze slashes
pattern = new(RegExp)(pattern, ignoreCase ? 'i' : '');
context.routes.push(route = {
pattern: pattern,
method: method,
constraints: constraints
});
return {
bind: function (handler) {
route.handler = handler;
return route;
}
};
},
path: function (pattern, map) {
this.paths.push(pattern.exec ? pattern.source
: escapeRe(pattern));
map.call(this, this);
this.paths.pop();
},
trail: function (from, to) {
// Logging
}
};
};
journey.Router.prototype = {
// Called when the HTTP request is 'complete'
// and ready to be processed.
route: function (request, body, callback) {
var promise = new(events.EventEmitter);
var request = Object.create(request);
var that = this;
request.url = url.parse(request.url);
// Call the router asynchronously, so we can return a promise
process.nextTick(function () {
// Dispatch the HTTP request:
// As the last argument, we send the function to be called when the response is ready
// to be sent back to the client -- this allows us to keep our entry and exit point
// in the same spot. `outcome` is an object with a `status`, a `body` and `headers`
that.dispatch(request, body || "", function (outcome) {
outcome.headers["Date"] = new(Date)().toUTCString();
outcome.headers["Server"] = "journey/" + journey.version.join('.');
if (outcome.body) {
outcome.headers["Content-Type"] = "application/json";
if (typeof(outcome.body) !== 'string') {
outcome.body = JSON.stringify(outcome.body);
}
outcome.headers['Content-Length'] = outcome.body.length;
} else {
delete(outcome.headers["Content-Type"]);
}
if (callback) { callback(outcome) }
else { promise.emit("success", outcome) }
promise.emit("log", new(Date)().toUTCString() +
" -- " + request.method + " " +
request.url.href + " - HTTP " + outcome.status);
});
});
return promise;
},
constraints: {
//
// Check if the request has a non-empty body
//
payload: function (payload, request, body) {
return Boolean(body) === payload;
},
//
// Run a function, and check return value
//
assert: function (assert, request, body) {
return Boolean(assert(request, body));
}
},
resolve: function (request, body) {
var that = this, allowedMethods = [];
//
// Return the first matching route
//
var found = find(this.routes, function (route) {
// Match the pattern with the url
var match = (function (pattern) {
var path = request.url.pathname;
if (! path) { throw new(BadRequest) }
return (path.length > 1 ? path.slice(1) : path).match(pattern);
})(route.pattern);
//
// Run through the specified constraints,
// making sure everything passes.
//
var constraints = Object.keys(route.constraints).length === 0 ? true :
Object.keys(route.constraints).every(function (key) {
// Check if the constraint has been defined, then run it.
if (key in that.constraints) {
return that.constraints[key](route.constraints[key], request, body);
} else {
throw new(Error)("constraint '" + key + "' not found.");
}
});
if (match && constraints) {
if (! ('handler' in route)) { throw new(NotImplemented)("unbound route") }
if ((Array.isArray(route.method) && route.method.indexOf(request.method) !== -1) ||
(route.method === request.method) || !route.method) {
return function (res, params) {
var args = [];
args.push(res);
args.push.apply(args, match.slice(1).map(function (m) {
return /^\d+$/.test(m) ? parseInt(m) : m;
}));
args.push(params);
return route.handler.apply(this, args);
};
} else {
if (allowedMethods.indexOf(route.method) === -1) {
allowedMethods.push(route.method);
}
return false;
}
}
return false;
});
if (found) {
return found;
} else if (allowedMethods.length) {
throw new(MethodNotAllowed)(allowedMethods.join(','));
} else {
return false;
}
},
// This function glues together the request resolver, with the responder.
// It creates a new `route` context, in which the response will be generated.
dispatch: function (request, body, respond) {
var resolved, route, parser,
params = querystring.parse(request.url.query || ''),
accepts = request.headers.accept;
accepts = accepts && accepts.split(/[,;] */);
// Journey being a JSON-only server, we expect the 'Accept' header
// to be set accordingly.
if (this.options.strict) {
if (!accepts || accepts.indexOf("application/json") === -1) {
return respond(new(NotAcceptable)(request.headers.accept));
}
} else {
if (accepts && accepts.indexOf("application/json") === -1 &&
accepts.indexOf("*/*") === -1) {
return respond(new(NotAcceptable)(request.headers.accept));
}
}
try {
resolved = this.resolve(request, body);
} catch (e) {
if (e.status) { // If it's an HTTP Error
return respond({
headers: e.headers || {},
status: e.status,
body: JSON.stringify(e.body)
});
} else {
throw e;
}
}
route = this.draw(request, respond);
if (resolved) {
if (body) {
parser = /^application\/json/.test(
request.headers["content-type"]
) ? JSON.parse : querystring.parse;
try {
body = parser(body);
} catch (e) {
return respond(new(BadRequest)("malformed data"));
}
// If the body is an Array, we want to return params as an array,
// else, an object. The `mixin` function will preserve the type
// of its first parameter.
params = Array.isArray(body) ? mixin(body, params) : mixin(params, body);
}
return route.go(resolved, params);
} else {
return respond(new(NotFound)("request not found"));
}
},
// A constructor of sorts, which returns a 'Routing context', in which the response
// status is evaluated.
draw: function (req, respond) {
return {
request: req,
respond: respond,
baseResponse: {
status: req.method == 'POST' ? 201 : 200,
body: "",
headers: {"Content-Type" : "application/json"}
},
// A wrapper around `respond()`, it allows us to respond in a variety of
// ways, such as: `201`, `"Hello World"`, `[201, "Hello", {'Content-Type':'text/html'}]`, etc.
// All parameters are optional.
responder: function (response) {
// If more than one argument was received, treat it as if it was an array.
if (arguments.length > 1) { response = Array.prototype.slice.apply(arguments) }
this.respond((function (baseResponse) {
switch (typeOf(response)) {
case "object":
return mixin({}, baseResponse, { body: response });
case "string":
return mixin({}, baseResponse, { body: { journey: response } });
case "number":
return mixin({}, baseResponse, { status: response });
case "array":
if (response.length === 3) {
return {
status: response[0],
headers: response[1],
body: response[2]
};
} else {
throw new(Error)("expected 3 elements in response");
}
default:
throw new(Error)("wrong response type");
}
})(this.baseResponse));
},
sendBody: function (body) {
this.respond(mixin({}, this.baseResponse, { body: body }));
},
sendHeaders: function (status, headers) {
this.respond(mixin({}, this.baseResponse, { status: status, headers: headers }));
},
go: function (destination, params) {
this.send = this.responder;
try {
destination.call(this, this, params || {});
} catch (err) {
this.respond({
body: { error: err.message || err,
stack: err.stack && err.stack.split('\n') },
status: err.status || 500, headers: {}
});
}
}
}
}
};
//
// Utility functions
//
function typeOf(value) {
var s = typeof(value),
types = [Object, String, RegExp, Number, Function, Boolean, Date];
if (Array.isArray(value)) {
return 'array';
} else if (s === 'object' || s === 'function') {
if (value) {
types.forEach(function (t) {
if (value instanceof t) { s = t.name.toLowerCase() }
});
} else { s = 'null' }
}
return s;
}
function mixin(target) {
var args = Array.prototype.slice.call(arguments, 1);
args.forEach(function (a) {
var keys = Object.keys(a);
for (var i = 0; i < keys.length; i++) {
target[keys[i]] = a[keys[i]];
}
});
return target;
}
function find(array, fun) {
for (var i = 0; i < array.length; i++) {
if (ret = fun(array[i])) return ret;
}
return false;
}