-
Notifications
You must be signed in to change notification settings - Fork 58
/
router.ts
122 lines (118 loc) · 3.11 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
import {
IRouter,
RequestHandlerContext,
OpenSearchDashboardsRequest,
OpenSearchDashboardsResponseFactory,
IOpenSearchDashboardsResponse,
} from '../../../src/core/server';
import { schema } from '@osd/config-schema';
type RouteHandler = (
context: RequestHandlerContext,
request: OpenSearchDashboardsRequest,
response: OpenSearchDashboardsResponseFactory
) => Promise<IOpenSearchDashboardsResponse<any>>;
type Route = (path: string, handler: RouteHandler) => Router;
export interface Router {
get: Route;
post: Route;
put: Route;
delete: Route;
}
// Router factory
export default (iRouter: IRouter, basePath: String): Router => {
if (basePath == null || basePath == '') {
throw new TypeError('Base path is null');
}
const requestHandler =
(handler: RouteHandler) =>
async (
context: RequestHandlerContext,
request: OpenSearchDashboardsRequest,
response: OpenSearchDashboardsResponseFactory
) => {
try {
return await handler(context, request, response);
} catch (e) {
throw e;
}
};
return ['get', 'put', 'post', 'delete'].reduce(
(router: any, method: string) => {
router[method] = (path: String, handler: RouteHandler) => {
switch (method) {
case 'get': {
iRouter.get(
{
path: `${basePath}${path}`,
validate: {
params: schema.any(),
query: schema.any(),
body: schema.any(),
},
},
requestHandler(handler)
);
break;
}
case 'put': {
iRouter.put(
{
path: `${basePath}${path}`,
validate: {
params: schema.any(),
query: schema.any(),
body: schema.any(),
},
},
requestHandler(handler)
);
break;
}
case 'post': {
iRouter.post(
{
path: `${basePath}${path}`,
validate: {
params: schema.any(),
query: schema.any(),
body: schema.any(),
},
},
requestHandler(handler)
);
break;
}
case 'delete': {
iRouter.delete(
{
path: `${basePath}${path}`,
validate: {
params: schema.any(),
query: schema.any(),
body: schema.any(),
},
},
requestHandler(handler)
);
break;
}
default: {
break;
}
}
};
return router;
},
{}
);
};