UNPKG

3.13 kBJavaScriptView Raw
1const http = require('http');
2const Router = require('trouter');
3const { parse } = require('querystring');
4const parser = require('@polka/url');
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 onError(err, req, res, next) {
21 let code = (res.statusCode = err.code || err.status || 500);
22 res.end(err.length && err || err.message || http.STATUS_CODES[code]);
23}
24
25class Polka extends Router {
26 constructor(opts={}) {
27 super(opts);
28 this.apps = {};
29 this.wares = [];
30 this.bwares = {};
31 this.parse = parser;
32 this.server = opts.server;
33 this.handler = this.handler.bind(this);
34 this.onError = opts.onError || onError; // catch-all handler
35 this.onNoMatch = opts.onNoMatch || this.onError.bind(null, { code:404 });
36 }
37
38 add(method, pattern, ...fns) {
39 let base = lead(value(pattern));
40 if (this.apps[base] !== void 0) throw new Error(`Cannot mount ".${method.toLowerCase()}('${lead(pattern)}')" because a Polka application at ".use('${base}')" already exists! You should move this handler into your Polka application instead.`);
41 return super.add(method, pattern, ...fns);
42 }
43
44 use(base, ...fns) {
45 if (typeof base === 'function') {
46 this.wares = this.wares.concat(base, fns);
47 } else if (base === '/') {
48 this.wares = this.wares.concat(fns);
49 } else {
50 base = lead(base);
51 fns.forEach(fn => {
52 if (fn instanceof Polka) {
53 this.apps[base] = fn;
54 } else {
55 let arr = this.bwares[base] || [];
56 arr.length > 0 || arr.push((r, _, nxt) => (mutate(base, r),nxt()));
57 this.bwares[base] = arr.concat(fn);
58 }
59 });
60 }
61 return this; // chainable
62 }
63
64 listen() {
65 (this.server = this.server || http.createServer()).on('request', this.handler);
66 this.server.listen.apply(this.server, arguments);
67 return this;
68 }
69
70 handler(req, res, info) {
71 info = info || this.parse(req);
72 let fns=[], arr=this.wares, obj=this.find(req.method, info.pathname);
73 req.originalUrl = req.originalUrl || req.url;
74 let base = value(req.path = info.pathname);
75 if (this.bwares[base] !== void 0) {
76 arr = arr.concat(this.bwares[base]);
77 }
78 if (obj) {
79 fns = obj.handlers;
80 req.params = obj.params;
81 } else if (this.apps[base] !== void 0) {
82 mutate(base, req); info.pathname=req.path; //=> updates
83 fns.push(this.apps[base].handler.bind(null, req, res, info));
84 } else if (fns.length === 0) {
85 fns.push(this.onNoMatch);
86 }
87 // Grab addl values from `info`
88 req.search = info.search;
89 req.query = parse(info.query);
90 // Exit if only a single function
91 let i=0, len=arr.length, num=fns.length;
92 if (len === i && num === 1) return fns[0](req, res);
93 // Otherwise loop thru all middlware
94 let next = err => err ? this.onError(err, req, res, next) : loop();
95 let loop = _ => res.finished || (i < len) && arr[i++](req, res, next);
96 arr = arr.concat(fns);
97 len += num;
98 loop(); // init
99 }
100}
101
102module.exports = opts => new Polka(opts);