From 980741843520a4dbe9a733ff09a47ec2dfa75bc2 Mon Sep 17 00:00:00 2001 From: Daan Vanden Bosch Date: Thu, 2 Dec 2021 17:25:18 +0100 Subject: [PATCH] Improved Karma config. The middleware now caches files in memory and sends the correct content-type header for json files. --- .../resources/world/phantasmal/karmaConfig.js | 43 ++++++++++++++----- 1 file changed, 33 insertions(+), 10 deletions(-) diff --git a/buildSrc/src/main/resources/world/phantasmal/karmaConfig.js b/buildSrc/src/main/resources/world/phantasmal/karmaConfig.js index d274f41c..61e2ce6b 100644 --- a/buildSrc/src/main/resources/world/phantasmal/karmaConfig.js +++ b/buildSrc/src/main/resources/world/phantasmal/karmaConfig.js @@ -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');