Skip to content

Allow API store consumers to use traditional flow-control

Konrad Mohrfeldt requested to merge kmohrf/flow-control into master

This MR implements a solution that helps us to gradually migrate away from the callback-pattern used in the API store methods.

I’ve stumbled on this while looking for ways to solve #93 (closed), because the current callback-approach makes it quite hard to implement proper error handling in the view handlers that are calling the store methods.

Basically it allows us to refactor a function like this:

submitSchedule(ctx, data) {
    ctx.commit('loading', 'schedules')
    let uri = process.env.VUE_APP_API_STEERING_SHOWS + data.showId + '/schedules/'
    axios.post(uri, data.schedule, {
        withCredentials: true,
        headers: {'Authorization': 'Bearer ' + ctx.rootState.auth.user.access_token}
    }).then(response => {
        ctx.commit('finishLoading', 'schedules')
        if (data && typeof (data.callback) === 'function') {
            data.callback(response)
        }
    }).catch(error => {
        handleApiError(this, error, 'could not load timeslots')
        if (data && typeof (data.callbackCancel) === 'function') {
            data.callbackCancel()
        }
    })
}

into this:

submitSchedule(ctx, data) {
    ctx.commit('loading', 'schedules')
    let uri = process.env.VUE_APP_API_STEERING_SHOWS + data.showId + '/schedules/'
    return axios.post(uri, data.schedule, {
        withCredentials: true,
        headers: {'Authorization': 'Bearer ' + ctx.rootState.auth.user.access_token}
    }).then(response => {
        ctx.commit('finishLoading', 'schedules')
        return callOrReturn(response, data?.callback)
    }).catch(error => {
        APIError.handle(error, 'Unable to submit schedule', data, this)
    })
}

Whether or not callbacks are called is based on the caller of the function by either passing callbacks or not. If callbacks are provided we assume that the caller relies on them to handle the response data. If they are not provided we assume that the caller wants to handle Promise objects. This is tangentially related to #55 (closed), though strictly speaking this change is more about enabling the caller to properly handle errors than it is about the specific syntax used.

More details on the implementation and motivation can be found in 180ba939.

This MR is based on !9 (merged) which should be merged before.

Edited by Konrad Mohrfeldt

Merge request reports

Loading