Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 38 additions & 20 deletions resources/js/fetch.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { fetchCart } from './stores/useCart.js'
import { addFetch } from './stores/useFetches.js'
import { token } from './stores/useUser'
import { mask } from './stores/useMask.js'
import { token } from './stores/useUser.js'

export class FetchError extends Error {
constructor(message, response) {
Expand Down Expand Up @@ -123,6 +125,7 @@ export const magentoGraphQL = (window.magentoGraphQL = async (
headers: {},
redirectOnExpiration: true,
notifyOnError: true,
retryOnCartError: true,
},
) => {
let response = await rapidezFetch(config.magento_url + '/graphql', {
Expand All @@ -148,25 +151,40 @@ export const magentoGraphQL = (window.magentoGraphQL = async (
let data = await response.json()

if (data?.errors) {
console.error(data.errors)

data?.errors?.forEach((error) => {
if (!['graphql-authorization', 'graphql-authentication'].includes(error?.extensions?.category)) {
return
}

if (options?.notifyOnError ?? true) {
Notify(window.config.translations.errors.session_expired, 'error')
}

if (options?.redirectOnExpiration ?? true) {
window.$emit('logout', { redirect: '/login' })
} else {
throw new SessionExpired(window.config.translations.errors.session_expired, responseClone)
}
})

throw new GraphQLError(data.errors, responseClone)
// Filter out errors with a message that contain the cart id, signifying an expired cart
let errors = data.errors.filter((error) => !(mask.value.length > 0 && error.message.includes(mask.value)))
let cartErrors = data.errors.filter((error) => mask.value.length > 0 && error.message.includes(mask.value))

if (errors.length) {
console.error(data.errors)
errors.forEach((error) => {
if (!['graphql-authorization', 'graphql-authentication'].includes(error?.extensions?.category)) {
return
}

if (options?.notifyOnError ?? true) {
Notify(window.config.translations.errors.session_expired, 'error')
}

if (options?.redirectOnExpiration ?? true) {
window.$emit('logout', { redirect: '/login' })
} else {
throw new SessionExpired(window.config.translations.errors.session_expired, responseClone)
}
})

throw new GraphQLError(data.errors, responseClone)
} else if (cartErrors.length) {
// Get a new cart and redo the query with updated cart id
await fetchCart()
window.Notify(window.config.translations.errors.cart_expired, 'warning')

return await window.magentoGraphQL(
query,
{ ...variables, cartId: mask.value, cart_id: mask.value },
{ ...options, retryOnCartError: false },
)
}
}

if (!response.ok) {
Expand Down
Loading