UNPKG

2.9 kBJavaScriptView Raw
1import { pathToRegexp } from 'path-to-regexp';
2export var Priority;
3(function (Priority) {
4 Priority[Priority["LAST"] = 0] = "LAST";
5 Priority[Priority["LATER"] = 1] = "LATER";
6 Priority[Priority["MIDDLE"] = 2] = "MIDDLE";
7 Priority[Priority["EARLY"] = 3] = "EARLY";
8 Priority[Priority["FIRST"] = 4] = "FIRST";
9})(Priority || (Priority = {}));
10export class FABRouter {
11 constructor() {
12 this.pipeline = {
13 [Priority.LAST]: [],
14 [Priority.LATER]: [],
15 [Priority.MIDDLE]: [],
16 [Priority.EARLY]: [],
17 [Priority.FIRST]: [],
18 };
19 }
20 getPipeline() {
21 return [
22 ...this.pipeline[Priority.FIRST],
23 ...this.pipeline[Priority.EARLY],
24 ...this.pipeline[Priority.MIDDLE],
25 ...this.pipeline[Priority.LATER],
26 ...this.pipeline[Priority.LAST],
27 ];
28 }
29 addToPipeline(responder, priority = Priority.MIDDLE) {
30 this.pipeline[priority].push(responder);
31 }
32 on(route, responder, priority) {
33 if (route === '*') {
34 // Make this an alias for .onAll, with an empty params object
35 this.onAll((context) => responder({ ...context, params: {} }), priority);
36 }
37 else {
38 // Otherwise compile the route and generate a responder
39 const groups = [];
40 const regexp = pathToRegexp(route, groups);
41 this.addToPipeline(async (context) => {
42 const { pathname } = context.url;
43 // Only execute if this request matches our route
44 const match = regexp.exec(pathname);
45 if (match) {
46 const params = {};
47 groups.forEach((group, i) => {
48 params[group.name] = match[i + 1];
49 });
50 return await responder({ ...context, params });
51 }
52 return undefined;
53 }, priority);
54 }
55 }
56 onAll(responder, priority) {
57 this.addToPipeline(responder, priority);
58 }
59 interceptResponse(interceptor, priority = Priority.EARLY) {
60 this.addToPipeline(async (context) => {
61 return {
62 interceptResponse: interceptor,
63 };
64 }, priority);
65 }
66}
67export class FABRuntime {
68 constructor(metadata, file_metadata, context) {
69 this.Metadata = metadata;
70 this.FileMetadata = file_metadata;
71 this.Router = new FABRouter();
72 this.ServerContext = context;
73 }
74 static initialize(metadata, plugins, context) {
75 const instance = new FABRuntime(metadata.plugin_metadata, metadata.file_metadata, context);
76 plugins.forEach((plugin) => plugin(instance));
77 return instance;
78 }
79 getPipeline() {
80 return this.Router.getPipeline();
81 }
82}
83//# sourceMappingURL=runtime.js.map
\No newline at end of file