import uniqueId from 'lodash/utility/uniqueId'; import { isFSA } from 'flux-standard-action'; function mergeMeta(action, meta) { return {...action.meta, ...meta}; } export default function webWorkerMiddleware(scriptURL) { let dispatch = null; const worker = new Worker(scriptURL); worker.onmessage = (e) => { if (dispatch && isFSA(e.data)) { dispatch(e.data); } }; return methods => { dispatch = methods.dispatch; return next => action => { if (!isFSA(action) || !action.meta || !action.meta.background) { return next(action); } const backgroundTaskId = uniqueId('bt'); worker.postMessage({ ...action, meta: mergeMeta(action, { backgroundTaskId, background: false }) }); next({ ...action, meta: mergeMeta(action, { backgroundTaskId, sequence: 'begin' }) }); return backgroundTaskId; } } }