Added cancellable requests for AxiosStrategy

This commit is contained in:
Andrew Bastin
2020-05-30 18:26:26 -04:00
parent e2e1432069
commit b2600d3ffd

View File

@@ -1,39 +1,69 @@
import axios from "axios" import axios from "axios"
let cancelSource = axios.CancelToken.source()
export const cancelRunningAxiosRequest = () => {
cancelSource.cancel()
// Create a new cancel token
cancelSource = axios.CancelToken.source()
}
const axiosWithProxy = async (req, { state }) => { const axiosWithProxy = async (req, { state }) => {
const { data } = await axios.post( try {
state.postwoman.settings.PROXY_URL || "https://postwoman.apollosoftware.xyz/", const { data } = await axios.post(
req state.postwoman.settings.PROXY_URL || "https://postwoman.apollosoftware.xyz/",
) req,
return data {
cancelToken: cancelSource.token,
}
)
return data
} catch (e) {
// Check if the throw is due to a cancellation
if (axios.isCancel(e)) {
throw "cancellation"
} else {
throw e
}
}
} }
const axiosWithoutProxy = async (req, _store) => { const axiosWithoutProxy = async (req, _store) => {
const res = await axios({ try {
...req, const res = await axios({
transformResponse: [ ...req,
(data, headers) => { cancelToken: cancelSource.token,
// If the response has a JSON content type, try parsing it transformResponse: [
if ( (data, headers) => {
headers["content-type"] && // If the response has a JSON content type, try parsing it
(headers["content-type"].startsWith("application/json") || if (
headers["content-type"].startsWith("application/vnd.api+json") || headers["content-type"] &&
headers["content-type"].startsWith("application/hal+json")) (headers["content-type"].startsWith("application/json") ||
) { headers["content-type"].startsWith("application/vnd.api+json") ||
try { headers["content-type"].startsWith("application/hal+json"))
const jsonData = JSON.parse(data) ) {
return jsonData try {
} catch (e) { const jsonData = JSON.parse(data)
return data return jsonData
} catch (e) {
return data
}
} }
}
// Else return the string itself without any transformations // Else return the string itself without any transformations
return data return data
}, },
], ],
}) })
return res return res
} catch (e) {
if (axios.isCancel(e)) {
throw "cancellation"
} else {
throw e
}
}
} }
const axiosStrategy = (req, store) => { const axiosStrategy = (req, store) => {