front-hub/src/api/cart.ts
2023-11-06 02:48:07 +03:00

86 lines
2.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { UserAccount, makeRequest } from "@frontend/kitui"
import { AxiosError } from "axios"
import { parseAxiosError } from "@root/utils/parse-error"
const apiUrl =
process.env.NODE_ENV === "production"
? "/customer"
: "https://hub.pena.digital/customer"
export async function patchCart(
tariffId: string
): Promise<[string[], string?]> {
try {
const patchCartResponse = await makeRequest<never, UserAccount>({
url: apiUrl + `/cart?id=${tariffId}`,
method: "PATCH",
useToken: true,
})
return [patchCartResponse.cart]
} catch (nativeError) {
let [error, status] = parseAxiosError(nativeError)
if (status === 400 && error.indexOf("invalid id") !== -1) error = "Данный тариф более недоступен"
return [[], `Не удалось добавить товар в корзину. ${error}`]
}
}
export async function deleteCart(
tariffId: string
): Promise<[string[], string?]> {
try {
const deleteCartResponse = await makeRequest<never, UserAccount>({
url: apiUrl + `/cart?id=${tariffId}`,
method: "DELETE",
useToken: true,
})
return [deleteCartResponse.cart]
} catch (nativeError) {
const [error] = parseAxiosError(nativeError)
return [[], `Не удалось удалить товар из корзины. ${error}`]
}
}
export async function payCart(): Promise<[UserAccount | null, string?]> {
try {
const payCartResponse = await makeRequest<never, UserAccount>({
url: apiUrl + "/cart/pay",
method: "POST",
useToken: true,
})
return [payCartResponse]
} catch (nativeError) {
const [error] = parseAxiosError(nativeError)
return [null, `Не удалось оплатить товар из корзины. ${error}`]
}
}
export async function patchCurrency(
currency: string
): Promise<[UserAccount | null, string?]> {
try {
const patchCurrencyResponse = await makeRequest<
{ currency: string },
UserAccount
>({
url: apiUrl + "/wallet",
method: "PATCH",
useToken: true,
body: {
currency,
},
})
return [patchCurrencyResponse]
} catch (nativeError) {
const [error] = parseAxiosError(nativeError)
return [null, `Не удалось изменить валюту. ${error}`]
}
}