react-native-unit-components
Version:
Unit React Native components
59 lines (52 loc) • 2 kB
text/typescript
import axios from 'axios';
import { APIHeaders, UNIT_SECURE_URL } from '../common/UNNetworkConstants';
import type { UNMobileWalletPayload } from '../../helpers/pushProvisioningService/types';
import type { UNError, UNErrorData } from '../../types/shared/error.types';
import { UNEnvironment } 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: UNEnvironment, 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 UNEnvironment]}/cards/${cardId}/mobile-wallet-payload`;
try {
const response = await axios.post(
baseURL,
data,
{
headers: headers,
});
if (!isUNMobileWalletPayload(response.data)) {
const error: UNErrorData = {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 UNError
if (axios.isAxiosError<UNError>(error) && error.response) {
const unErrors = error.response.data;
throw unErrors;
} else if (error instanceof Error) {
const unexpectedError: UNErrorData = {title: 'Unexpected error', error: error};
throw unexpectedError;
}
throw {title: `Unexpected error: ${error}`};
}
};