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