forked from lindsaykwardell/http-wrapper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Router.ts
65 lines (57 loc) · 1.92 KB
/
Router.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import {
ServerRequest,
} from "https://deno.land/std/http/server.ts";
import { Endpoint, EndpointMap } from "./types.ts";
export class Router {
private root: string = "/";
constructor(root = "/") {
this.root = root;
}
private _get: EndpointMap = new Map();
private _post: EndpointMap = new Map();
private _put: EndpointMap = new Map();
private _delete: EndpointMap = new Map();
public get(route: string, func: (req: ServerRequest) => void) {
const withoutSlash = route === "/" ? "" : route.replace(/(\/\/)/g, "/");
const withSlash = withoutSlash + "/";
this._get.set(withoutSlash, func);
if (!(withoutSlash === "" && this.root === "/")) {
this._get.set(withSlash, func);
}
}
public post(route: string, func: (req: ServerRequest) => void) {
const withoutSlash = route === "/" ? "" : route.replace(/(\/\/)/g, "/");
const withSlash = withoutSlash + "/";
this._post.set(withoutSlash, func);
if (!(withoutSlash === "" && this.root === "/")) {
this._post.set(withSlash, func);
}
}
public put(route: string, func: (req: ServerRequest) => void) {
const withoutSlash = route === "/" ? "" : route.replace(/(\/\/)/g, "/");
const withSlash = withoutSlash + "/";
this._put.set(withoutSlash, func);
if (!(withoutSlash === "" && this.root === "/")) {
this._put.set(withSlash, func);
}
}
public delete(route: string, func: (req: ServerRequest) => void) {
const withoutSlash = route === "/" ? "" : route.replace(/(\/\/)/g, "/");
const withSlash = withoutSlash + "/";
this._delete.set(withoutSlash, func);
if (!(withoutSlash === "" && this.root === "/")) {
this._delete.set(withSlash, func);
}
}
public get routes(): Endpoint {
return {
uri: this.root,
routes: {
getRoutes: this._get,
postRoutes: this._post,
putRoutes: this._put,
deleteRoutes: this._delete,
},
};
}
}