|
1
|
import { dynamicImport, isFileSkipped, readDirRecursive } from "@medusajs/utils" |
|
2
|
import { join, parse, sep } from "path" |
|
3
|
import { logger } from "../logger" |
|
4
|
import { HTTP_METHODS, type RouteDescriptor, type RouteVerb } from "./types" |
|
5
|
|
|
6
|
/** |
|
7
|
* File name that is used to indicate that the file is a route file |
|
8
|
*/ |
|
9
|
const ROUTE_NAME = "route" |
|
10
|
|
|
11
|
/** |
|
12
|
* Flag that developers can export from their route files to indicate |
|
13
|
* whether or not the routes from this file should be authenticated. |
|
14
|
*/ |
|
15
|
const AUTHTHENTICATION_FLAG = "AUTHENTICATE" |
|
16
|
|
|
17
|
/** |
|
18
|
* Flag that developers can export from their route files to indicate |
|
19
|
* whether or not the routes from this file should implement CORS |
|
20
|
* policy. |
|
21
|
*/ |
|
22
|
const CORS_FLAG = "CORS" |
|
23
|
|
|
24
|
/** |
|
25
|
* The matcher to use to convert the dynamic params from the filesystem |
|
26
|
* identifier to the express identifier. |
|
27
|
* |
|
28
|
* We capture all words under opening and closing brackets `[]` and mark |
|
29
|
* it as a param via `:`. |
|
30
|
*/ |
|
31
|
const PARAM_SEGMENT_MATCHER = /\[(\w+)\]/ |
|
32
|
|
|
33
|
/** |
|
34
|
* Regexes to use to identify if a route is prefixed |
|
35
|
* with "/admin", "/store", or "/auth". |
|
36
|
*/ |
|
37
|
const ADMIN_ROUTE_MATCH = /(\/admin$|\/admin\/)/ |
|
38
|
const STORE_ROUTE_MATCH = /(\/store$|\/store\/)/ |
|
39
|
const AUTH_ROUTE_MATCH = /(\/auth$|\/auth\/)/ |
|
40
|
|
|
41
|
/** |
|
42
|
* Exposes to API to register routes manually or by scanning the filesystem from a |
|
43
|
* source directory. |
|
44
|
* |
|
45
|
* In case of duplicates routes, the route registered afterwards will override the |
|
46
|
* one registered first. |
|
47
|
*/ |
|
48
|
export class RoutesLoader { |
|
49
|
/** |
|
50
|
* Routes collected manually or by scanning directories |
|
51
|
*/ |
|
52
|
#routes: Record<string, Record<string, RouteDescriptor>> = {} |
|
53
|
|
|
54
|
/** |
|
55
|
* Creates the route path from its relative file path. |
|
56
|
*/ |
|
57
|
createRoutePath(relativePath: string): string { |
|
58
|
const segments = relativePath.replace(/route(\.js|\.ts)$/, "").split(sep) |
|
59
|
const params: Record<string, boolean> = {} |
|
60
|
|
|
61
|
return `/${segments |
|
62
|
.filter((segment) => !!segment) |
|
63
|
.map((segment) => { |
|
64
|
if (segment.startsWith("[")) { |
|
65
|
segment = segment.replace(PARAM_SEGMENT_MATCHER, (_, group) => { |
|
66
|
if (params[group]) { |
|
67
|
logger.debug( |
|
68
|
`Duplicate parameters found in route ${relativePath} (${group})` |
|
69
|
) |
|
70
|
|
|
71
|
throw new Error( |
|
72
|
`Duplicate parameters found in route ${relativePath} (${group}). Make sure that all parameters are unique.` |
|
73
|
) |
|
74
|
} |
|
75
|
|
|
76
|
params[group] = true |
|
77
|
return `:${group}` |
|
78
|
}) |
|
79
|
} |
|
80
|
return segment |
|
81
|
}) |
|
82
|
.join("/")}` |
|
83
|
} |
|
84
|
|
|
85
|
/** |
|
86
|
* Returns the route config by exporting the route file and parsing |
|
87
|
* its exports |
|
88
|
*/ |
|
89
|
async #getRoutesForFile( |
|
90
|
routePath: string, |
|
91
|
absolutePath: string |
|
92
|
): Promise<RouteDescriptor[]> { |
|
93
|
const routeExports = await dynamicImport(absolutePath) |
|
94
|
|
|
95
|
if (isFileSkipped(routeExports)) { |
|
96
|
return [] |
|
97
|
} |
|
98
|
|
|
99
|
/** |
|
100
|
* Find the route type based upon its prefix. |
|
101
|
*/ |
|
102
|
const routeType = ADMIN_ROUTE_MATCH.test(routePath) |
|
103
|
? "admin" |
|
104
|
: STORE_ROUTE_MATCH.test(routePath) |
|
105
|
? "store" |
|
106
|
: AUTH_ROUTE_MATCH.test(routePath) |
|
107
|
? "auth" |
|
108
|
: undefined |
|
109
|
|
|
110
|
/** |
|
111
|
* Check if the route file has decided to opt-out of authentication |
|
112
|
*/ |
|
113
|
const shouldAuthenticate = |
|
114
|
AUTHTHENTICATION_FLAG in routeExports |
|
115
|
? !!routeExports[AUTHTHENTICATION_FLAG] |
|
116
|
: true |
|
117
|
|
|
118
|
/** |
|
119
|
* Check if the route file has decided to opt-out of CORS |
|
120
|
*/ |
|
121
|
const shouldApplyCors = |
|
122
|
CORS_FLAG in routeExports ? !!routeExports[CORS_FLAG] : true |
|
123
|
|
|
124
|
/** |
|
125
|
* Loop over all the exports and collect functions that are exported |
|
126
|
* with names after HTTP methods. |
|
127
|
*/ |
|
128
|
return Object.keys(routeExports) |
|
129
|
.filter((key) => { |
|
130
|
if (typeof routeExports[key] !== "function") { |
|
131
|
return false |
|
132
|
} |
|
133
|
|
|
134
|
if (!HTTP_METHODS.includes(key as RouteVerb)) { |
|
135
|
logger.debug( |
|
136
|
`Skipping handler ${key} in ${absolutePath}. Invalid HTTP method: ${key}.` |
|
137
|
) |
|
138
|
return false |
|
139
|
} |
|
140
|
|
|
141
|
return true |
|
142
|
}) |
|
143
|
.map((key) => { |
|
144
|
return { |
|
145
|
isRoute: true, |
|
146
|
matcher: routePath, |
|
147
|
method: key as RouteVerb, |
|
148
|
handler: routeExports[key], |
|
149
|
optedOutOfAuth: !shouldAuthenticate, |
|
150
|
shouldAppendAdminCors: shouldApplyCors && routeType === "admin", |
|
151
|
shouldAppendAuthCors: shouldApplyCors && routeType === "auth", |
|
152
|
shouldAppendStoreCors: shouldApplyCors && routeType === "store", |
|
153
|
} satisfies RouteDescriptor |
|
154
|
}) |
|
155
|
} |
|
156
|
|
|
157
|
/** |
|
158
|
* Scans a given directory and loads all routes from it. You can access the loaded |
|
159
|
* routes via "getRoutes" method |
|
160
|
*/ |
|
161
|
async scanDir(sourceDir: string) { |
|
162
|
const entries = await readDirRecursive(sourceDir, { |
|
163
|
ignoreMissing: true, |
|
164
|
}) |
|
165
|
|
|
166
|
await Promise.all( |
|
167
|
entries |
|
168
|
.filter((entry) => { |
|
169
|
if (entry.isDirectory()) { |
|
170
|
return false |
|
171
|
} |
|
172
|
|
|
173
|
const { name, ext } = parse(entry.name) |
|
174
|
if (name === ROUTE_NAME && [".js", ".ts"].includes(ext)) { |
|
175
|
const routeFilePathSegment = join(entry.path, entry.name) |
|
176
|
.replace(sourceDir, "") |
|
177
|
.split(sep) |
|
178
|
|
|
179
|
return !routeFilePathSegment.some((segment) => |
|
180
|
segment.startsWith("_") |
|
181
|
) |
|
182
|
} |
|
183
|
|
|
184
|
return false |
|
185
|
}) |
|
186
|
.map(async (entry) => { |
|
187
|
const absolutePath = join(entry.path, entry.name) |
|
188
|
const relativePath = absolutePath.replace(sourceDir, "") |
|
189
|
const route = this.createRoutePath(relativePath) |
|
190
|
const routes = await this.#getRoutesForFile(route, absolutePath) |
|
191
|
|
|
192
|
routes.forEach((routeConfig) => { |
|
193
|
this.registerRoute({ |
|
194
|
absolutePath, |
|
195
|
relativePath, |
|
196
|
...routeConfig, |
|
197
|
}) |
|
198
|
}) |
|
199
|
}) |
|
200
|
) |
|
201
|
} |
|
202
|
|
|
203
|
/** |
|
204
|
* Register a route |
|
205
|
*/ |
|
206
|
registerRoute(route: RouteDescriptor) { |
|
207
|
this.#routes[route.matcher] = this.#routes[route.matcher] ?? {} |
|
208
|
const trackedRoute = this.#routes[route.matcher] |
|
209
|
trackedRoute[route.method] = route |
|
210
|
} |
|
211
|
|
|
212
|
/** |
|
213
|
* Register one or more routes |
|
214
|
*/ |
|
215
|
registerRoutes(routes: RouteDescriptor[]) { |
|
216
|
routes.forEach((route) => this.registerRoute(route)) |
|
217
|
} |
|
218
|
|
|
219
|
/** |
|
220
|
* Returns an array of routes scanned by the routes loader or registered |
|
221
|
* manually. |
|
222
|
*/ |
|
223
|
getRoutes() { |
|
224
|
return Object.keys(this.#routes).reduce<RouteDescriptor[]>( |
|
225
|
(result, routePattern) => { |
|
226
|
const methodsRoutes = this.#routes[routePattern] |
|
227
|
Object.keys(methodsRoutes).forEach((method) => { |
|
228
|
const route = methodsRoutes[method] |
|
229
|
result.push(route) |
|
230
|
}) |
|
231
|
return result |
|
232
|
}, |
|
233
|
[] |
|
234
|
) |
|
235
|
} |
|
236
|
|
|
237
|
/** |
|
238
|
* Reload a single route file |
|
239
|
* This is used by HMR to reload routes when files change |
|
240
|
*/ |
|
241
|
async reloadRouteFile( |
|
242
|
absolutePath: string, |
|
243
|
sourceDir: string |
|
244
|
): Promise<RouteDescriptor[]> { |
|
245
|
const relativePath = absolutePath.replace(sourceDir, "") |
|
246
|
const route = this.createRoutePath(relativePath) |
|
247
|
const routes = await this.#getRoutesForFile(route, absolutePath) |
|
248
|
|
|
249
|
// Register the new routes (will overwrite existing) |
|
250
|
routes.forEach((routeConfig) => { |
|
251
|
this.registerRoute({ |
|
252
|
absolutePath, |
|
253
|
relativePath, |
|
254
|
...routeConfig, |
|
255
|
}) |
|
256
|
}) |
|
257
|
|
|
258
|
return routes.map((routeConfig) => ({ |
|
259
|
absolutePath, |
|
260
|
relativePath, |
|
261
|
...routeConfig, |
|
262
|
})) |
|
263
|
} |
|
264
|
} |