UNPKG

exome

Version:

State manager for deeply nested states

8 lines (7 loc) 2.66 kB
{ "version": 3, "sources": ["../src/utils.ts"], "sourcesContent": ["/**\n * @module exome/utils\n */\nimport { type Exome, addMiddleware, getExomeId, update } from \"exome\";\n\ninterface ActionStatus<E = any, R = any> {\n\tloading: boolean;\n\terror: false | E;\n\tresponse: void | R;\n\tunsubscribe: () => void;\n}\n\nconst actionStatusCache: Record<string, ActionStatus> = {};\n\n/**\n * Subscribes to specific action in specific instance and returns satus about that action.\n */\nexport function getActionStatus<E = Error, T extends Exome = any, R = any>(\n\tstore: T,\n\taction: keyof T,\n): ActionStatus<E, R> {\n\tconst key = getExomeId(store) + \":\" + (action as string);\n\tlet cached = actionStatusCache[key];\n\n\tif (cached) {\n\t\treturn cached;\n\t}\n\n\tcached = actionStatusCache[key] = {\n\t\tloading: false,\n\t\terror: false,\n\t\tresponse: undefined,\n\t\tunsubscribe() {\n\t\t\tunsubscribe();\n\t\t\tactionStatusCache[key] = undefined as any;\n\t\t},\n\t};\n\n\tlet actionIndex = 0;\n\n\tconst unsubscribe = addMiddleware((instance, targetAction, payload) => {\n\t\tif (instance !== store || targetAction !== action || !cached) {\n\t\t\treturn;\n\t\t}\n\n\t\tactionIndex++;\n\t\tconst currentActionIndex = actionIndex;\n\t\tcached.loading = true;\n\t\tcached.error = false;\n\t\tcached.response = undefined;\n\n\t\tupdate(instance);\n\n\t\treturn (error, response) => {\n\t\t\tif (currentActionIndex !== actionIndex || !cached) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tcached.loading = false;\n\t\t\tcached.error = error || false;\n\t\t\tcached.response = response || undefined;\n\n\t\t\tupdate(instance);\n\t\t};\n\t});\n\n\treturn cached;\n}\n"], "mappings": ";AAGA,SAAqB,iBAAAA,GAAe,cAAAC,GAAY,UAAAC,SAAc;AAS9D,IAAMC,IAAkD,CAAC;AAKlD,SAASC,EACfC,GACAC,GACqB;AACrB,MAAMC,IAAMN,EAAWI,CAAK,IAAI,MAAOC,GACnCE,IAASL,EAAkBI,CAAG;AAElC,MAAIC;AACH,WAAOA;AAGR,EAAAA,IAASL,EAAkBI,CAAG,IAAI;AAAA,IACjC,SAAS;AAAA,IACT,OAAO;AAAA,IACP,UAAU;AAAA,IACV,cAAc;AACb,MAAAE,EAAY,GACZN,EAAkBI,CAAG,IAAI;AAAA,IAC1B;AAAA,EACD;AAEA,MAAIG,IAAc,GAEZD,IAAcT,EAAc,CAACW,GAAUC,GAAcC,MAAY;AACtE,QAAIF,MAAaN,KAASO,MAAiBN,KAAU,CAACE;AACrD;AAGD,IAAAE;AACA,QAAMI,IAAqBJ;AAC3B,WAAAF,EAAO,UAAU,IACjBA,EAAO,QAAQ,IACfA,EAAO,WAAW,QAElBN,EAAOS,CAAQ,GAER,CAACI,GAAOC,MAAa;AAC3B,MAAIF,MAAuBJ,KAAe,CAACF,MAI3CA,EAAO,UAAU,IACjBA,EAAO,QAAQO,KAAS,IACxBP,EAAO,WAAWQ,KAAY,QAE9Bd,EAAOS,CAAQ;AAAA,IAChB;AAAA,EACD,CAAC;AAED,SAAOH;AACR;", "names": ["addMiddleware", "getExomeId", "update", "actionStatusCache", "getActionStatus", "store", "action", "key", "cached", "unsubscribe", "actionIndex", "instance", "targetAction", "payload", "currentActionIndex", "error", "response"] }