MCPcopy Create free account
hub / github.com/developit/stockroom / createStore

Function createStore

src/index.js:18–125  ·  view source on GitHub ↗
(worker)

Source from the content-addressed store, hash-verified

16 * let store = createStore(new StoreWorker)
17 */
18export default function createStore(worker) {
19 let listeners = [],
20 state = {},
21 sendQueue = [],
22 initialized = false;
23
24 function handleMessage({ data }) {
25 if (typeof data!=='object') {}
26 else if ('pop' in data) {
27 if (data.length===1) {
28 process(data[0]);
29 }
30 else {
31 for (let i=0; i<data.length; i++) process(data[i]);
32 }
33 }
34 else {
35 process(data);
36 }
37 }
38
39 function process(data) {
40 let { type, overwrite, update, action, initial, partial } = data;
41
42 if (type==='@@STATE') {
43 if (partial===true) {
44 update = applyUpdate(state, update);
45 overwrite = true;
46 }
47
48 setState(update, overwrite===true, action, false);
49
50 if (initial) {
51 initialized = true;
52 processSendQueue();
53 }
54 }
55 }
56
57
58 worker.addEventListener('message', handleMessage);
59
60 function setState(update, overwrite, action, replicate) {
61 let oldState = state;
62 state = assign(overwrite ? {} : assign({}, state), update);
63 if (replicate) {
64 let update = overwrite ? state : diff(state, oldState);
65 send({ type: '@@STATE', overwrite, update, action, partial: !overwrite });
66 // send({ type: '@@STATE', overwrite, update, action });
67 }
68 let currentListeners = listeners;
69 for (let i=0; i<currentListeners.length; i++) currentListeners[i](state, action);
70 }
71
72 function send(opts) {
73 if (sendQueue.push(opts)===1) {
74 setTimeout(processSendQueue);
75 }

Callers 5

backstore.test.jsFile · 0.85
worker.fixture.jsFile · 0.85
createWorkerStoreFunction · 0.85
store.jsFile · 0.85
store-worker.jsFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected