christianmalek / vuex-rest-api

A utility to simplify the use of REST APIs with Vuex
http://vuex-rest-api.org
MIT License
382 stars 48 forks source link

Axios config passthrough and cancellation #106

Closed pchisholm closed 3 years ago

pchisholm commented 3 years ago

Changes

Request Cancellation

Auto Cancellation:

autoCancel can now be set in ShorthandResourceActionOptions. This cancels a previous / pending request for a given action and ignores handling the resulting cancellation error, effectively suspending the pending state. However, if a non-cancellation error occurs (say a user gets rate limited or the server crashes) the normal error handling flow will resume.

This is most useful when an action can lead to data races because of some hard to control user behavior or interaction. In our app, we see this often when filtering lists of objects, etc. This is much easier to reason about than trying to write boiler plate code to make sure a resulting payload is safe to set or merge into the store in onSuccess.

Code example:

.get({
  autoCancel: true,
  action: "getItemsLongRunningAutoCancel",
  property: "itemsAuto",
  path: "/long-running"
})

Live example:

auto-cancel

Manual Cancellation:

Added a source property to the action states so axios cancel sources can be easily referenced / mapped to components for situations where autoCancel isn't useful (say you want to let the user deliberately cancel something).

Code example:

(see tests/src/components/CancelTest.vue in this pr for a more detailed example)

if (this.foo.source.bar) {
  this.foo.source.bar.cancel()
}

Live Example:

manual-cancel

Manual Cancellation - Controlled:

Let's say you didn't want to use a cancel source set by the library to handle cancelling for some reason, you can supply your own now that AxiosRequestConfig is being passed through. This is a good example of both changes made in this PR.

Code example:

(see tests/src/components/CancelTest.vue in this pr for a more detailed example)

const CancelToken = axios.CancelToken
const source = CancelToken.source()

try {
  await doGetFoo({
    cancelToken: source.token
  })
} catch (e) {
  console.error(e)
}

Notes

christianmalek commented 3 years ago

Thank you Patrick for your efforts! I'll check the PR in the next 30 days and merge it if everything seems fine.

pchisholm commented 3 years ago

Thank you Patrick for your efforts! I'll check the PR in the next 30 days and merge it if everything seems fine.

Awesome! Sounds good & thanks for getting back to me so quickly. If all is well on your end when you get some time to review, I can update the docs branch at that point with the new config options. 👍

pchisholm commented 3 years ago

@christianmalek I've decided to close this PR for the time being as my team is going to fork the repo for future maintenance purposes. Feel free to re-open this though if you want to use any of the code down the line!