UNPKG

@actorize/core

Version:

Actorize helps building scalable js apps with a messaging system

77 lines 2.85 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const defaultStorage_1 = __importDefault(require("./defaultStorage")); function createRemoteStorageProvider(director, opts) { const { actorName, defaultValue } = opts; const { storage = (0, defaultStorage_1.default)(defaultValue) } = opts; // @ts-expect-error for now ok const actor = director.registerActor(actorName); const keysSubscribed = {}; const localStore = { set: async (key, value) => { await storage.set(key, value); if (!keysSubscribed[key]) { return; } keysSubscribed[key].forEach((recp) => { // @ts-expect-error for now ok actor.sendMessage(recp, { event: 'KEY_UPDATED', key, value, }); }); }, get: async (key) => { const val = await storage.get(key); return val; }, delete: async (key) => { await storage.delete(key); }, }; actor.onMessage((msgs) => { msgs.forEach(async (tmp) => { // TODO: just a workaround const msg = tmp; if (msg.payload.action === 'SUBSCRIBE_TO_KEYS' && msg.payload.keys) { msg.payload.keys.forEach((key) => { if (!keysSubscribed[key]) { keysSubscribed[key] = []; } keysSubscribed[key].push(msg.sender); }); } if (msg.payload.action === 'UNSUBSCRIBE_FROM_KEYS' && msg.payload.keys) { msg.payload.keys.forEach((key) => { if (!keysSubscribed[key]) { return; } keysSubscribed[key] = keysSubscribed[key].filter((elem) => elem !== msg.sender); }); } if (msg.payload.action === 'SET' && msg.payload.key && msg.payload.value !== undefined) { localStore.set(msg.payload.key, msg.payload.value); } if (msg.payload.action === 'GET' && msg.payload.key) { const resp = await localStore.get(msg.payload.key); // @ts-expect-error for now ok actor.sendMessage(msg.sender, { event: 'GET_RETURN', value: resp, }); } }); }); return localStore; } exports.default = createRemoteStorageProvider; //# sourceMappingURL=remoteStorageProvider.js.map