-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
80 lines (68 loc) · 1.93 KB
/
index.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import * as express from 'express'
type Method = 'get' | 'post' | 'put' | 'patch' | 'delete'
interface RouteItem {
method: Method
path: string
action: string
}
export const registerControllers = (props: {
router: express.Router
controllers: Array<new () => any>
middlewares?: express.Handler[]
}) => {
const { router, controllers, middlewares } = props
controllers.forEach(controller => {
registerController({ router, controller, middlewares })
})
}
export const registerController = (props: {
router: express.Router
controller: new () => any
middlewares?: express.Handler[]
}) => {
const instance = new props.controller()
instance._routes.forEach((route: RouteItem) => {
const path = instance._basePath + route.path
props.router[route.method](
path,
...(props.middlewares ?? []),
(instance as any)[route.action].bind(instance)
)
})
}
export const Controller = (basePath: string) => {
// return Class Decorator
return <T extends new (...args: any[]) => {}>(target: T) => {
return class RouteController extends target {
_basePath = basePath
constructor(...args: any[]) {
super(...args)
}
}
}
}
export const Get = (path?: string): MethodDecorator => {
return MethodFactory('get', path)
}
export const Post = (path?: string): MethodDecorator => {
return MethodFactory('post', path)
}
export const Put = (path?: string): MethodDecorator => {
return MethodFactory('put', path)
}
export const Patch = (path?: string): MethodDecorator => {
return MethodFactory('patch', path)
}
export const Delete = (path?: string): MethodDecorator => {
return MethodFactory('delete', path)
}
const MethodFactory = (method: Method, path?: string) => {
return (
target: any,
property: string | symbol,
_descriptor: PropertyDescriptor
) => {
target._routes = target._routes ?? []
target._routes.push({ method, path: path ?? '', action: property })
}
}