-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
get-static-file.ts
51 lines (43 loc) · 1.21 KB
/
get-static-file.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
import { getParsedUrl, getPathNameFromUrl } from "../route/route.utils.ts";
import { send } from "../static/send.ts";
import { StaticFilesConfig } from "../models/static-config.ts";
import { HttpContext } from "../models/http-context.ts";
export async function getStaticFile<T>(
context: HttpContext<T>,
staticConfig?: StaticFilesConfig,
showError: boolean = true,
) {
if (staticConfig == null) {
return false;
}
let url = context.request.url;
// TODO use Normal parser with UrlParser
const parserUrl = getParsedUrl(url);
let pathName = parserUrl.pathname;
if (staticConfig.baseRoute) {
const regexpUrl = new RegExp(`^${staticConfig.baseRoute}`);
if (regexpUrl.test(parserUrl.pathname)) {
pathName = pathName.replace(regexpUrl, "/");
} else {
return false;
}
}
url = parserUrl.origin + pathName;
try {
const filePath = await send(
{
request: context.request.serverRequest.request,
response: context.response,
},
getPathNameFromUrl(url),
staticConfig,
);
return !!filePath;
} catch (error) {
// TODO: exception
if (staticConfig.baseRoute && showError) {
console.warn(error);
}
return null;
}
}