Improved Karma config. The middleware now caches files in memory and sends the correct content-type header for json files.

This commit is contained in:
Daan Vanden Bosch 2021-12-02 17:25:18 +01:00
parent 3e17865346
commit 9807418435

View File

@ -1,19 +1,39 @@
config.middleware = config.middleware || [];
config.middleware.push('resource-loader');
function ResourceLoaderMiddleware() {
const fs = require('fs');
const fs = require('fs/promises');
const cache = new Map;
return async function (request, response, next) {
const path = decodeURI(request.originalUrl);
const isJson = path.slice(-5) === '.json';
function sendContent(content) {
if (isJson) {
response.setHeader('Content-Type', 'application/json');
}
return function (request, response, next) {
try {
const content = fs.readFileSync(PROJECT_PATH + '/build/processedResources/js/test' + decodeURI(request.originalUrl));
response.writeHead(200);
response.end(content);
}
async function tryBasePath(basePath) {
const content = await fs.readFile(PROJECT_PATH + basePath + path)
cache.set(path, content);
sendContent(content);
}
const cached = cache.get(path);
if (cached) {
sendContent(cached);
return;
}
try {
await tryBasePath('/build/processedResources/js/test');
} catch (ignored) {
try {
const content = fs.readFileSync(PROJECT_PATH + '/build/processedResources/js/main' + decodeURI(request.originalUrl));
response.writeHead(200);
response.end(content);
await tryBasePath('/build/processedResources/js/main');
} catch (ignored) {
next();
}
@ -24,3 +44,6 @@ function ResourceLoaderMiddleware() {
config.plugins.push({
'middleware:resource-loader': ['factory', ResourceLoaderMiddleware]
});
config.middleware = config.middleware || [];
config.middleware.push('resource-loader');