UNPKG

1.6 kBJavaScriptView Raw
1'use strict';
2
3var HttpHash = require('http-hash');
4var url = require('url');
5var TypedError = require('error/typed');
6var extend = require('xtend');
7var httpMethods = require('http-methods/method');
8
9var ExpectedCallbackError = TypedError({
10 type: 'http-hash-router.expected.callback',
11 message: 'http-hash-router: Expected a callback to be ' +
12 'passed as the 4th parameter to handleRequest.\n' +
13 'SUGGESTED FIX: call the router with ' +
14 '`router(req, res, opts, cb).\n',
15 value: null
16});
17var NotFoundError = TypedError({
18 type: 'http-hash-router.not-found',
19 message: 'Resource Not Found',
20 statusCode: 404
21});
22
23module.exports = HttpHashRouter;
24
25function HttpHashRouter() {
26 var hash = HttpHash();
27
28 handleRequest.hash = hash;
29 handleRequest.set = set;
30
31 return handleRequest;
32
33 function set(name, handler) {
34 if (handler && typeof handler === 'object') {
35 handler = httpMethods(handler);
36 }
37
38 return hash.set(name, handler);
39 }
40
41 function handleRequest(req, res, opts, cb) {
42 if (typeof cb !== 'function') {
43 throw ExpectedCallbackError({
44 value: cb
45 });
46 }
47
48 var pathname = url.parse(req.url).pathname;
49
50 var route = hash.get(pathname);
51 if (route.handler === null) {
52 return cb(NotFoundError({
53 pathname: pathname
54 }));
55 }
56
57 opts = extend(opts, {
58 params: route.params,
59 splat: route.splat
60 });
61 return route.handler(req, res, opts, cb);
62 }
63}