Stackedit/src/store/queue.js

84 lines
2.3 KiB
JavaScript
Raw Normal View History

2017-08-15 10:43:26 +00:00
const setter = propertyName => (state, value) => {
state[propertyName] = value;
};
let queue = Promise.resolve();
export default {
namespaced: true,
state: {
isEmpty: true,
isSyncRequested: false,
2017-09-23 19:01:50 +00:00
isPublishRequested: false,
currentLocation: {},
2017-08-15 10:43:26 +00:00
},
mutations: {
setIsEmpty: setter('isEmpty'),
setIsSyncRequested: setter('isSyncRequested'),
2017-09-23 19:01:50 +00:00
setIsPublishRequested: setter('isPublishRequested'),
setCurrentLocation: setter('currentLocation'),
2017-08-15 10:43:26 +00:00
},
actions: {
2017-09-23 19:01:50 +00:00
enqueue({ state, commit, dispatch }, cb) {
2017-09-26 22:54:26 +00:00
if (state.offline) {
// No need to enqueue
return;
}
2017-09-23 19:01:50 +00:00
const checkOffline = () => {
if (state.offline) {
// Empty queue
queue = Promise.resolve();
commit('setIsEmpty', true);
throw new Error('offline');
}
};
2017-08-15 10:43:26 +00:00
if (state.isEmpty) {
commit('setIsEmpty', false);
}
const newQueue = queue
2017-09-23 19:01:50 +00:00
.then(() => checkOffline())
2017-11-26 20:58:24 +00:00
.then(() => Promise.resolve()
.then(() => cb())
2017-09-23 19:01:50 +00:00
.catch((err) => {
console.error(err); // eslint-disable-line no-console
checkOffline();
dispatch('notification/error', err, { root: true });
})
.then(() => {
if (newQueue === queue) {
commit('setIsEmpty', true);
}
}));
2017-08-15 10:43:26 +00:00
queue = newQueue;
},
enqueueSyncRequest({ state, commit, dispatch }, cb) {
if (!state.isSyncRequested) {
commit('setIsSyncRequested', true);
const unset = () => commit('setIsSyncRequested', false);
2017-08-17 23:10:35 +00:00
dispatch('enqueue', () => cb().then(unset, (err) => {
unset();
throw err;
}));
2017-08-15 10:43:26 +00:00
}
},
2017-09-23 19:01:50 +00:00
enqueuePublishRequest({ state, commit, dispatch }, cb) {
if (!state.isSyncRequested) {
commit('setIsPublishRequested', true);
const unset = () => commit('setIsPublishRequested', false);
dispatch('enqueue', () => cb().then(unset, (err) => {
unset();
throw err;
}));
}
},
2018-05-13 13:27:33 +00:00
async doWithLocation({ commit }, { location, action }) {
try {
commit('setCurrentLocation', location);
return await action();
} finally {
commit('setCurrentLocation', {});
}
2017-09-23 19:01:50 +00:00
},
2017-08-15 10:43:26 +00:00
},
};