UNPKG

react-native-unit-components

Version:

Unit React Native components

59 lines (52 loc) 2.12 kB
import axios from 'axios'; import { APIHeaders, UNIT_SECURE_URL } from '../common/UNNetworkConstants'; import type { UNMobileWalletPayload } from '../../helpers/pushProvisioningService/types'; import type { UNComponentsError, UNComponentsErrorData } from '../../types/shared/error.types'; import { UNComponentsEnvironment } from '../../types/shared/env.types'; // eslint-disable-next-line @typescript-eslint/no-explicit-any const isUNMobileWalletPayload = (object: any): object is UNMobileWalletPayload => { return 'data' in object && 'attributes' in object.data && 'payload' in object.data.attributes; }; // TODO: use apiClient class for handling requests. export const getMobileWalletPayload = async (customerToken: string, cardId: string, env: UNComponentsEnvironment, signedNonce: string) => { if (!signedNonce) return; const headers = { 'Content-Type': APIHeaders.CONTENT_TYPE, 'Authorization': `Bearer ${customerToken}`, }; const data = { data: { attributes: { signedNonce: signedNonce, }, }, }; const baseURL = `${UNIT_SECURE_URL[env as keyof typeof UNComponentsEnvironment]}/cards/${cardId}/mobile-wallet-payload`; try { const response = await axios.post( baseURL, data, { headers: headers, }); if (!isUNMobileWalletPayload(response.data)) { const error: UNComponentsErrorData = { title: `Couldn't get mobile wallet payload. Status:${response.status} Response data:${response.data}` }; throw error; } else { const encryptedPayload = response.data.data.attributes.payload; return encryptedPayload; } } catch (error: unknown) { // Converts the error into a UNComponentsError if (axios.isAxiosError<UNComponentsError>(error) && error.response) { const unComponentsErrors = error.response.data; throw unComponentsErrors; } else if (error instanceof Error) { const unexpectedError: UNComponentsErrorData = { title: 'Unexpected error', error: error }; throw unexpectedError; } throw { title: `Unexpected error: ${error}` }; } };