Add optional callback to Vuex API action.

The callback has the signature (err, res) where
res is the result object from the fetch() request
and err is non-null if an error occurred and fetch()
threw.

The callback is called before res.json() has had a
chance to run it is really not recommended to
consume the body from this callback as this will cause
an error in the API action itself.
This commit is contained in:
D. Berge
2020-09-27 19:23:04 +02:00
parent fd1f1a2c1a
commit 371030e61e

View File

@@ -1,5 +1,5 @@
async function api ({state, commit, dispatch}, [resource, init = {}]) {
async function api ({state, commit, dispatch}, [resource, init = {}, cb]) {
try {
commit("queueRequest");
if (init && init.hasOwnProperty("body")) {
@@ -14,6 +14,9 @@ async function api ({state, commit, dispatch}, [resource, init = {}]) {
}
}
const res = await fetch(`${state.apiUrl}${resource}`, init);
if (typeof cb === 'function') {
cb(null, res);
}
if (res.ok) {
try {
return await res.json();
@@ -33,6 +36,9 @@ async function api ({state, commit, dispatch}, [resource, init = {}]) {
} catch (err) {
if (err && err.name == "AbortError") return;
await dispatch('showSnack', [err, "error"]);
if (typeof cb === 'function') {
cb(err);
}
} finally {
commit("dequeueRequest");
}