UNPKG

2.96 kBJavaScriptView Raw
1const http = require('http');
2const Router = require('trouter');
3const parser = require('@polka/url');
4const { parse } = require('querystring');
5
6function lead(x) {
7 return x.charCodeAt(0) === 47 ? x : ('/' + x);
8}
9
10function value(x) {
11 let y = x.indexOf('/', 1);
12 return y > 1 ? x.substring(0, y) : x;
13}
14
15function mutate(str, req) {
16 req.url = req.url.substring(str.length) || '/';
17 req.path = req.path.substring(str.length) || '/';
18}
19
20function isRootWild(obj) {
21 return Object.keys(obj).length === 1 && obj['*'];
22}
23
24function onError(err, req, res, next) {
25 let code = (res.statusCode = err.code || err.status || 500);
26 res.end(err.length && err || err.message || http.STATUS_CODES[code]);
27}
28
29class Polka extends Router {
30 constructor(opts={}) {
31 super(opts);
32 this.apps = {};
33 this.wares = [];
34 this.bwares = {};
35 this.parse = parser;
36 this.server = opts.server;
37 this.handler = this.handler.bind(this);
38 this.onError = opts.onError || onError; // catch-all handler
39 this.onNoMatch = opts.onNoMatch || this.onError.bind(null, { code:404 });
40 }
41
42 use(base, ...fns) {
43 if (typeof base === 'function') {
44 this.wares = this.wares.concat(base, fns);
45 } else if (base === '/') {
46 this.wares = this.wares.concat(fns);
47 } else {
48 base = lead(base);
49 fns.forEach(fn => {
50 if (fn instanceof Polka) {
51 this.apps[base] = fn;
52 } else {
53 let arr = this.bwares[base] || [];
54 (arr.length === 0) && arr.push((r, _, nxt) => (mutate(base, r),nxt()));
55 this.bwares[base] = arr.concat(fn);
56 }
57 });
58 }
59 return this; // chainable
60 }
61
62 listen() {
63 (this.server = this.server || http.createServer()).on('request', this.handler);
64 this.server.listen.apply(this.server, arguments);
65 return this;
66 }
67
68 handler(req, res, info) {
69 info = info || this.parse(req);
70 let fns=[], arr=this.wares, obj=this.find(req.method, info.pathname);
71 req.originalUrl = req.originalUrl || req.url;
72 req.path = info.pathname;
73 if (obj) {
74 fns = obj.handlers;
75 req.params = obj.params;
76 }
77 if (!obj || isRootWild(obj.params)) {
78 // Looking for sub-apps or extra middleware
79 let base = value(req.path);
80 if (this.apps[base] !== void 0) {
81 mutate(base, req); info.pathname=req.path; //=> updates
82 fns.push(this.apps[base].handler.bind(null, req, res, info));
83 } else {
84 fns.length > 0 || fns.push(this.onNoMatch);
85 if (this.bwares[base] !== void 0) {
86 arr = arr.concat(this.bwares[base]);
87 }
88 }
89 }
90 // Grab addl values from `info`
91 req.search = info.search;
92 req.query = parse(info.query);
93 // Exit if only a single function
94 let i=0, len=arr.length, num=fns.length;
95 if (len === i && num === 1) return fns[0](req, res);
96 // Otherwise loop thru all middlware
97 let next = err => err ? this.onError(err, req, res, next) : loop();
98 let loop = _ => res.finished || (i < len) && arr[i++](req, res, next);
99 arr = arr.concat(fns);
100 len += num;
101 loop(); // init
102 }
103}
104
105module.exports = opts => new Polka(opts);