31 lines
940 B
JavaScript
31 lines
940 B
JavaScript
export class ResourceCache {
|
|
constructor(root) {
|
|
this.root = root;
|
|
this.handlers = new Map();
|
|
this.promises = new Map();
|
|
}
|
|
|
|
register(kind, handler) {
|
|
this.handlers.set(kind, handler);
|
|
}
|
|
|
|
get(id, kind) {
|
|
const [namespace, resource] = id.includes(':') ? id.split(':', 2) : ["minecraft", id];
|
|
id = `${namespace}:${resource}`;
|
|
const url = `${this.root}/${namespace}/${kind}/${resource}`;
|
|
|
|
const key = `${kind}:${namespace}:${resource}`;
|
|
if (this.promises.has(key)) return this.promises.get(key);
|
|
|
|
const handler = this.handlers.get(kind);
|
|
if (!handler) throw new Error(`No handler registered for resource kind: ${kind}`);
|
|
|
|
if (handler.prepare) {
|
|
handler.prepare(this, id, url);
|
|
}
|
|
|
|
const promise = handler.process(this, id, url);
|
|
this.promises.set(key, promise);
|
|
return promise;
|
|
}
|
|
} |