-
-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy pathFunctionalRouter.ts
60 lines (53 loc) · 1.7 KB
/
FunctionalRouter.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
import express, { NextFunction, Router } from "express"
import { Request, Response } from "./authentication.js"
// Little wrapper to automatically send returned objects as JSON, makes
// the API code a bit cleaner
export class FunctionalRouter {
router: Router
constructor() {
this.router = Router()
this.router.use(express.urlencoded({ extended: true }))
// Parse incoming requests with JSON payloads http://expressjs.com/en/api.html
this.router.use(express.json({ limit: "50mb" }))
}
wrap(callback: (req: Request, res: Response) => Promise<any>) {
return async (req: Request, res: Response, next: NextFunction) => {
try {
res.send(await callback(req, res))
} catch (e) {
console.error(e)
next(e)
}
}
}
get(
targetPath: string,
callback: (req: Request, res: Response) => Promise<any>
) {
this.router.get(targetPath, this.wrap(callback))
}
post(
targetPath: string,
callback: (req: Request, res: Response) => Promise<any>
) {
this.router.post(targetPath, this.wrap(callback))
}
patch(
targetPath: string,
callback: (req: Request, res: Response) => Promise<any>
) {
this.router.patch(targetPath, this.wrap(callback))
}
put(
targetPath: string,
callback: (req: Request, res: Response) => Promise<any>
) {
this.router.put(targetPath, this.wrap(callback))
}
delete(
targetPath: string,
callback: (req: Request, res: Response) => Promise<any>
) {
this.router.delete(targetPath, this.wrap(callback))
}
}