import { createApi, fetchBaseQuery, BaseQueryFn, FetchBaseQueryError, FetchBaseQueryMeta, FetchArgs, BaseQueryApi } from '@reduxjs/toolkit/query/react'; import settings from 'settings'; import { getCookie } from '../../utils'; import { RootState } from 'redux/store'; interface CustomBaseQueryApi extends BaseQueryApi { getState: () => RootState; } const customBaseQuery: BaseQueryFn< string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta > = async (args, api: CustomBaseQueryApi, extraOptions) => { const mutations = Object.entries(api.getState()?.api?.mutations ?? {}).map( (x) => x[1] ); if ( api.type === 'mutation' && mutations.filter( (m) => m.status === 'pending' && m.endpointName === api.endpoint ).length > 1 ) { api.abort('Mutation already in progress.'); } const baseQuery = fetchBaseQuery({ prepareHeaders: async (headers) => { const csrfCookie = getCookie('csrftoken'); const activeLocale = getCookie('pz-locale'); const localeApiValue = settings.localization.locales.find( (locale) => locale.value === activeLocale )?.apiValue; const activeCurrency = getCookie('pz-currency'); headers.set('Accept-Language', `${localeApiValue}`); headers.set('x-currency', `${activeCurrency}`); if (csrfCookie) { headers.set('x-csrftoken', `${csrfCookie}`); } return headers; }, credentials: 'include' }); try { const result = await baseQuery(args, api, extraOptions); return result; } catch (error) { return { error }; } }; export const api = createApi({ reducerPath: 'api', baseQuery: customBaseQuery, tagTypes: [ 'Basket', 'MultiBasket', 'MiniBasket', 'BasketB2b', 'DraftsB2b', 'Product', 'Checkout', 'PaymentOptions', 'Favorite', 'Addresses', 'Profile', 'StockAlert' ], endpoints: () => ({}) }); export const { util: { invalidateTags } } = api;