mirror of
https://github.com/DaanVandenBosch/phantasmal-world.git
synced 2025-04-04 06:28:28 +08:00
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:
parent
3e17865346
commit
9807418435
@ -1,19 +1,39 @@
|
|||||||
config.middleware = config.middleware || [];
|
|
||||||
config.middleware.push('resource-loader');
|
|
||||||
|
|
||||||
function ResourceLoaderMiddleware() {
|
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.writeHead(200);
|
||||||
|
|
||||||
response.end(content);
|
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) {
|
} catch (ignored) {
|
||||||
try {
|
try {
|
||||||
const content = fs.readFileSync(PROJECT_PATH + '/build/processedResources/js/main' + decodeURI(request.originalUrl));
|
await tryBasePath('/build/processedResources/js/main');
|
||||||
response.writeHead(200);
|
|
||||||
response.end(content);
|
|
||||||
} catch (ignored) {
|
} catch (ignored) {
|
||||||
next();
|
next();
|
||||||
}
|
}
|
||||||
@ -24,3 +44,6 @@ function ResourceLoaderMiddleware() {
|
|||||||
config.plugins.push({
|
config.plugins.push({
|
||||||
'middleware:resource-loader': ['factory', ResourceLoaderMiddleware]
|
'middleware:resource-loader': ['factory', ResourceLoaderMiddleware]
|
||||||
});
|
});
|
||||||
|
|
||||||
|
config.middleware = config.middleware || [];
|
||||||
|
config.middleware.push('resource-loader');
|
||||||
|
Loading…
Reference in New Issue
Block a user