Cache config.json

This commit is contained in:
RMidhunSuresh 2022-04-21 12:52:42 +05:30
parent 6cd3c8ee2b
commit 468b7e1595
3 changed files with 40 additions and 2 deletions

View File

@ -171,7 +171,7 @@ export class Platform {
if (!this._configURL) {
throw new Error("Neither config nor configURL was provided!");
}
const {body}= await this.request(this._configURL, {method: "GET", format: "json"}).response();
const {body}= await this.request(this._configURL, {method: "GET", format: "json", cache: true}).response();
this._config = body;
}
this._notificationService = new NotificationService(

View File

@ -75,7 +75,14 @@ self.addEventListener('fetch', (event) => {
This has to do with xhr not being supported in service workers.
*/
if (event.request.method === "GET") {
event.respondWith(handleRequest(event.request));
if (event.request.url.includes("config.json")) {
/**
* Use a different strategy for this file.
*/
event.respondWith(handleConfigRequest(event.request));
} else {
event.respondWith(handleRequest(event.request));
}
}
});
@ -119,6 +126,32 @@ async function handleRequest(request) {
}
}
async function handleConfigRequest(request) {
const url = new URL(request.url);
// rewrite / to /index.html so it hits the cache
if (url.origin === baseURL.origin && url.pathname === baseURL.pathname) {
request = new Request(new URL("index.html", baseURL.href));
}
let response = await readCache(request);
if (response) {
fetchAndUpdateConfig(request);
return response;
}
response = await fetchAndUpdateConfig(request);
return response;
}
async function fetchAndUpdateConfig(request) {
const response = await fetch(request, {
signal: pendingFetchAbortController.signal,
headers: {
"Cache-Control": "no-cache",
},
});
updateCache(request, response.clone());
return response;
}
async function updateCache(request, response) {
// don't write error responses to the cache
if (response.status >= 400) {

View File

@ -14,6 +14,11 @@ export default defineConfig(({mode}) => {
outDir: "../../../target",
minify: true,
sourcemap: true,
rollupOptions: {
output: {
assetFileNames: (asset) => asset.name.includes("config.json") ? "assets/[name][extname]": "assets/[name].[hash][extname]",
},
},
},
plugins: [
themeBuilder({