-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpublicFileResponse.mjs
More file actions
86 lines (70 loc) · 2.32 KB
/
publicFileResponse.mjs
File metadata and controls
86 lines (70 loc) · 2.32 KB
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
// @ts-check
/** @import { ResponseInit } from "./serve.mjs" */
import { STATUS_CODE, STATUS_TEXT } from "@std/http/status";
import { contentType } from "@std/media-types/content-type";
import { extname } from "@std/path/extname";
/**
* Creates a response for a public file request.
* @param {Request} request Request.
* @param {URL} publicDir Public directory file URL.
* @param {(
* request: Request,
* responseInit: ResponseInit
* ) => ResponseInit | Promise<ResponseInit>} [customizeResponseInit] Customizes
* the response init.
* @returns {Promise<Response>} Response that streams the public file.
*/
export default async function publicFileResponse(
request,
publicDir,
customizeResponseInit,
) {
if (!(request instanceof Request)) {
throw new TypeError("Argument 1 `request` must be a `Request` instance.");
}
if (!(publicDir instanceof URL)) {
throw new TypeError("Argument 2 `publicDir` must be a `URL` instance.");
}
if (!publicDir.href.endsWith("/")) {
throw new TypeError(
"Argument 2 `publicDir` must be a URL ending with `/`.",
);
}
if (
customizeResponseInit !== undefined &&
typeof customizeResponseInit !== "function"
) {
throw new TypeError(
"Argument 3 `customizeResponseInit` must be a function.",
);
}
const requestUrl = new URL(request.url);
const fileUrl = new URL("." + requestUrl.pathname, publicDir);
const file = await Deno.open(fileUrl);
try {
const { isFile } = await file.stat();
if (!isFile) throw new Deno.errors.NotFound();
/** @type {ResponseInit} */
let responseInit = {
status: STATUS_CODE.OK,
statusText: STATUS_TEXT[STATUS_CODE.OK],
headers: new Headers(),
};
const fileExtension = extname(fileUrl.pathname);
if (fileExtension) {
const contentTypeHeader = contentType(fileExtension);
if (contentTypeHeader) {
responseInit.headers.set("content-type", contentTypeHeader);
}
}
if (typeof customizeResponseInit === "function") {
responseInit = await customizeResponseInit(request, responseInit);
}
return new Response(file.readable, responseInit);
} catch (error) {
// Safely ensure the file is closed, see:
// https://github.com/denoland/deno/issues/14210#issuecomment-2600381752
file[Symbol.dispose]();
throw error;
}
}