grafana/public/app/features/plugins/pluginCacheBuster.ts
Marcus Andersson e5421dd53e
Chore: Change so we cache loading plugins by its version (#41367)
* making it possible to cache plugins based on the version.

* feat(plugincache): introduce function to invalidate entries

* removed todo's

* added tests for the cache buster.

* fixed tests.

* fixed failing tests.

Co-authored-by: Jack Westbrook <jack.westbrook@gmail.com>
2021-11-10 11:54:58 +01:00

46 lines
1.0 KiB
TypeScript

const cache: Record<string, string> = {};
const initializedAt: number = Date.now();
type CacheablePlugin = {
path: string;
version: string;
};
export function registerPluginInCache({ path, version }: CacheablePlugin): void {
if (!cache[path]) {
cache[path] = encodeURI(version);
}
}
export function invalidatePluginInCache(pluginId: string): void {
const path = `plugins/${pluginId}/module`;
if (cache[path]) {
delete cache[path];
}
}
export function locateWithCache(load: { address: string }, defaultBust = initializedAt): string {
const { address } = load;
const path = extractPath(address);
if (!path) {
return `${address}?_cache=${defaultBust}`;
}
const version = cache[path];
const bust = version || defaultBust;
return `${address}?_cache=${bust}`;
}
function extractPath(address: string): string | undefined {
const match = /\/public\/(plugins\/.+\/module)\.js/i.exec(address);
if (!match) {
return;
}
const [_, path] = match;
if (!path) {
return;
}
return path;
}