import { api } from './api'; import { user } from '../urls'; import { ForgotPasswordFormType, Order } from '../../types'; import { buildClientRequestUrl, getCookie } from '../../utils'; interface GetCaptchaResponse { siteKey: string; csrfToken: string; } interface ValidateCaptchaRequest { captchaResponse: string; csrfToken: string; } interface ValidateCaptchaResponse { success: boolean; } const userApi = api.injectEndpoints({ endpoints: (build) => ({ getCaptcha: build.query({ query: () => buildClientRequestUrl(user.captcha), transformResponse: (response: { html: string }) => { const siteKey = response.html.match(/data-sitekey="([^"]+)"/i)[1]; const csrfTokenMatch = response.html.match( /name=['|"]csrfmiddlewaretoken['|"] value=['|"][^'"]+/gi ); const csrfToken = csrfTokenMatch?.[0].replace( /name=['|"]csrfmiddlewaretoken['|"] value=['|"]/gi, '' ) || ''; return { siteKey, csrfToken }; } }), validateCaptcha: build.mutation< ValidateCaptchaResponse, ValidateCaptchaRequest >({ query: (body) => ({ url: buildClientRequestUrl(user.captcha, { useFormData: true }), method: 'POST', body: { 'g-recaptcha-response': body.captchaResponse } }), transformResponse: (response: { location: string }) => ({ success: response.location === '/' }) }), logout: build.mutation({ query: () => ({ url: '/api/logout', method: 'POST' }) }), forgotPassword: build.mutation({ query: (body) => { const frontendId = getCookie('pz-frontend-id'); const headers = frontendId ? { 'x-frontend-id': frontendId } : undefined; return { url: buildClientRequestUrl(user.forgotPassword, { contentType: 'application/json' }), method: 'POST', body, headers }; } }), otpLogin: build.mutation({ query: ({ phone }) => ({ url: buildClientRequestUrl(user.otpLogin, { contentType: 'application/json' }), method: 'POST', body: { phone } }) }), changeEmailVerification: build.query({ query: (token) => ({ url: buildClientRequestUrl(user.changeEmailVerification(token), { contentType: 'application/json' }) }) }), confirmEmailVerification: build.query({ query: (token) => ({ url: buildClientRequestUrl(user.confirmEmailVerification(token), { contentType: 'application/json' }) }) }), getAnonymousTracking: build.mutation< Order, { email: string; number: string } >({ query: ({ email, number }) => ({ url: buildClientRequestUrl(user.anonymousOrderTracking, { useFormData: true }), method: 'POST', body: { email, number } }) }) }), overrideExisting: false }); export const { useGetCaptchaQuery, useChangeEmailVerificationQuery, useConfirmEmailVerificationQuery, useValidateCaptchaMutation, useLogoutMutation, useOtpLoginMutation, useForgotPasswordMutation, useGetAnonymousTrackingMutation } = userApi;