UNPKG

1.43 kBJavaScriptView Raw
1"use strict";
2/** @format */
3Object.defineProperty(exports, "__esModule", { value: true });
4exports.Router = void 0;
5const composer_1 = require("./composer");
6class Router {
7 constructor(routeFn, handlers = new Map()) {
8 this.routeFn = routeFn;
9 this.handlers = handlers;
10 this.otherwiseHandler = composer_1.default.passThru();
11 if (typeof routeFn !== 'function') {
12 throw new Error('Missing routing function');
13 }
14 }
15 on(route, ...fns) {
16 if (fns.length === 0) {
17 throw new TypeError('At least one handler must be provided');
18 }
19 this.handlers.set(route, composer_1.default.compose(fns));
20 return this;
21 }
22 otherwise(...fns) {
23 if (fns.length === 0) {
24 throw new TypeError('At least one otherwise handler must be provided');
25 }
26 this.otherwiseHandler = composer_1.default.compose(fns);
27 return this;
28 }
29 middleware() {
30 return composer_1.default.lazy((ctx) => {
31 var _a;
32 const result = this.routeFn(ctx);
33 if (result == null) {
34 return this.otherwiseHandler;
35 }
36 Object.assign(ctx, result.context);
37 Object.assign(ctx.state, result.state);
38 return (_a = this.handlers.get(result.route)) !== null && _a !== void 0 ? _a : this.otherwiseHandler;
39 });
40 }
41}
42exports.Router = Router;