import { Events } from "../events/Events.js";
import { ConfigBroadcastChannel } from "../lib/config/Config.js";
/**
 * A class that caches user info in memory so the application reduces the number
 * of requests to the backend requesting a user info.
 */
class UserCache {
    constructor() {
        this.cached = new Map();
        /**
         * Application configuration broadcast channel.
         */
        this.configBroadcast = new BroadcastChannel(ConfigBroadcastChannel);
        this.configBroadcast.addEventListener('message', this.handleConfigBroadcast.bind(this));
    }
    async getUser(key) {
        const existing = this.cached.get(key);
        if (existing) {
            return existing;
        }
        const read = await this.requestUser(key);
        this.cached.set(key, read);
        return read;
    }
    async requestUser(key) {
        try {
            const result = await Events.Store.User.read(key);
            return result;
        }
        catch (e) {
            // ....
        }
        return undefined;
    }
    handleConfigBroadcast(e) {
        const event = e.data;
        const { path } = event;
        if (path === 'environment.setDefault') {
            this.cached = new Map();
        }
        else if (path === 'environment.add') {
            const init = event.init;
            if (init.asDefault) {
                this.cached = new Map();
            }
        }
    }
}
const instance = new UserCache();
export default instance;
//# sourceMappingURL=UserCache.js.map