feat: Support $MODULE_PATH in StaticAssetHandler

This commit is contained in:
Joachim Van Herwegen
2021-04-15 10:35:17 +02:00
parent 0a420847dc
commit e9917322e3
5 changed files with 91 additions and 6 deletions

View File

@@ -5,7 +5,7 @@ import { getLoggerFor } from '../../logging/LogUtil';
import { APPLICATION_OCTET_STREAM } from '../../util/ContentTypes';
import { NotFoundHttpError } from '../../util/errors/NotFoundHttpError';
import { NotImplementedHttpError } from '../../util/errors/NotImplementedHttpError';
import { joinFilePath } from '../../util/PathUtil';
import { joinFilePath, resolveAssetPath } from '../../util/PathUtil';
import { pipeSafely } from '../../util/StreamUtil';
import type { HttpHandlerInput } from '../HttpHandler';
import { HttpHandler } from '../HttpHandler';
@@ -13,6 +13,9 @@ import type { HttpRequest } from '../HttpRequest';
/**
* Handler that serves static resources on specific paths.
* Relative file paths are assumed to be relative to cwd.
* Relative file paths can be preceded by $PACKAGE_ROOT/, e.g. $PACKAGE_ROOT/foo/bar,
* in case they need to be relative to the module root.
*/
export class StaticAssetHandler extends HttpHandler {
private readonly mappings: Record<string, string>;
@@ -26,7 +29,10 @@ export class StaticAssetHandler extends HttpHandler {
*/
public constructor(assets: Record<string, string>) {
super();
this.mappings = { ...assets };
this.mappings = {};
for (const [ url, path ] of Object.entries(assets)) {
this.mappings[url] = resolveAssetPath(path);
}
this.pathMatcher = this.createPathMatcher(assets);
}

View File

@@ -165,3 +165,23 @@ export function createSubdomainRegexp(baseUrl: string): RegExp {
const { scheme, rest } = extractScheme(baseUrl);
return new RegExp(`^${scheme}(?:([^/]+)\\.)?${rest}`, 'u');
}
/**
* Returns the folder corresponding to the root of the Community Solid Server module
*/
export function getModuleRoot(): string {
return joinFilePath(__dirname, '../../');
}
/**
* Converts file path inputs into absolute paths.
* Works similar to `absoluteFilePath` but paths that start with '$PACKAGE_ROOT/'
* will be relative to the module directory instead of the cwd.
*/
export function resolveAssetPath(path: string): string {
const modulePath = '$PACKAGE_ROOT/';
if (path.startsWith(modulePath)) {
return joinFilePath(getModuleRoot(), path.slice(modulePath.length));
}
return absoluteFilePath(path);
}