-
Notifications
You must be signed in to change notification settings - Fork 0
/
createModulePreloadMiddleware.mjs
56 lines (47 loc) · 1.8 KB
/
createModulePreloadMiddleware.mjs
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
// @ts-check
import path from "node:path";
import createResolveLinkRelations from "modulepreload-link-relations/createResolveLinkRelations.mjs";
import formatLinkHeaderRelations from "modulepreload-link-relations/formatLinkHeaderRelations.mjs";
/** @typedef {import('express').RequestHandler} RequestHandler **/
/** @typedef {import('modulepreload-link-relations/createResolveLinkRelations.mjs').AsyncMapLike} AsyncMapLike */
const defaultOptions = {
extensions: ["mjs", "js"],
};
/**
* Creates a middleware function that adds a Link header containing modulepreload link relationships to JavaScript module requests.
* @param {string} appPath Path to the application root directory, eg "app".
* @param {Object} [userOptions] The options object.
* @param {Array<string>} [userOptions.extensions] The file extensions to consider for module scripts.
* @param {string} [userOptions.importMap] Import map.
* @param {AsyncMapLike} [userOptions.cache] A custom cache.
* @returns {RequestHandler} The middleware function.
*/
export default function createModulePreloadMiddleware(
appPath,
userOptions = {},
) {
const options = {
...defaultOptions,
...userOptions,
};
const resolveLinkRelations = createResolveLinkRelations(appPath, {
importMap: options.importMap,
cache: options.cache,
});
return async function modulePreloadMiddleware(req, res, next) {
try {
const url = req.url;
const file = req.url?.slice(1);
const fileExt = file && path.extname(file).slice(1);
if (fileExt && options.extensions.includes(fileExt)) {
const linkRelations = await resolveLinkRelations(url);
if (linkRelations) {
res.append("Link", formatLinkHeaderRelations(linkRelations));
}
}
next();
} catch (error) {
next(error);
}
};
}