From e423e446b992a1faaa8cbd91d80a2c6d646dcdd1 Mon Sep 17 00:00:00 2001 From: F-Node-Karlsruhe Date: Thu, 17 Nov 2022 16:49:50 +0100 Subject: [PATCH] add basic context caching --- api/src/services/documentLoader/index.ts | 28 ++++++++++++++++++------ 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/api/src/services/documentLoader/index.ts b/api/src/services/documentLoader/index.ts index c17d48c..503251d 100644 --- a/api/src/services/documentLoader/index.ts +++ b/api/src/services/documentLoader/index.ts @@ -2,7 +2,9 @@ import jsonldSignatures from 'jsonld-signatures'; import { getResolver } from './didresolver.js' -const BASE_CONTEXT_URL: string = 'https://ssi.eecc.de/api/registry/context' +const TRUSTED_CONTEXT_DOMAINS: [string] = ['https://ssi.eecc.de'] + +const cache = new Map(); const documentLoader: Promise = jsonldSignatures.extendContextLoader(async (url: string) => { @@ -42,18 +44,30 @@ const documentLoader: Promise = jsonldSignatures.extendContextLoader(async }; } - // Warn when context is fetched externally - // TODO create list of trusted sources - if (!url.startsWith(BASE_CONTEXT_URL)) console.warn(`Fetched @context from ${url}. Use with care!`) + let document = cache.get(url); + + // fetch if not in cache + if (!document) { + + document = await(await fetch(url)).json(); + + // cache and warn if external + if (!TRUSTED_CONTEXT_DOMAINS.some((trusted) => url.startsWith(trusted))) { + + console.warn(`Fetched and cached @context from ${url}. Use with care!`); - const document = await fetch(url); + cache.set(url, document); + + } + + } return { contextUrl: null, documentUrl: url, - document: await document.json(), + document: document, }; }); -export { documentLoader, BASE_CONTEXT_URL } \ No newline at end of file +export { documentLoader } \ No newline at end of file