'use client'; import { signOut } from 'next-auth/react'; import { ROUTES } from 'routes'; import type { Middleware } from '@reduxjs/toolkit'; import type { MiddlewareAction } from '../../types'; import { errorMiddleware, redirectUrlMiddleware, contextListMiddleware, hepsiPayMiddleware, walletPaymentMiddleware } from './checkout'; import { preOrderMiddlewares } from './pre-order'; import { api } from '../../data/client/api'; import logger from '@akinon/next/utils/log'; // Plugin middlewares import { savedCardMiddleware } from '@akinon/pz-saved-card'; import cyberSourceUcMiddleware from '@akinon/pz-cybersource-uc/src/redux/middleware'; export const rtkQueryResponseHandler: Middleware = () => (next) => (action) => { return next(action); }; export const rtkQueryErrorHandler: Middleware = () => (next) => async (action) => { const act = action as MiddlewareAction; if (act?.payload?.status === 401) { await signOut({ callbackUrl: `${ROUTES.AUTH}?callbackUrl=${window.location.pathname}` }); logger.debug('Session expired: 401'); return; } if (act?.payload?.status === 404) { logger.warn( `404 - Not Found. Endpoint: ${act.meta.arg.endpointName}, url: ${act.meta.baseQueryMeta.request.url}` ); } return next(action); }; const middlewares = [ api.middleware, rtkQueryResponseHandler, rtkQueryErrorHandler, errorMiddleware, redirectUrlMiddleware, ...preOrderMiddlewares, contextListMiddleware, hepsiPayMiddleware, walletPaymentMiddleware, savedCardMiddleware, cyberSourceUcMiddleware ]; // Filter out any non-function middleware to ensure all middlewares are valid and executable // This prevents runtime errors if any middleware is undefined or not properly initialized export default middlewares.filter( (middleware) => typeof middleware === 'function' );