83 lines
2.6 KiB
TypeScript
83 lines
2.6 KiB
TypeScript
import axios, { AxiosInstance } from 'axios';
|
|
import { HttpInstanceFactory } from '@/utils/HttpInstanceFactory';
|
|
import { IPlayer } from '@/interfaces/player.type';
|
|
import { toFixed } from '@/utils/FormatNumber';
|
|
|
|
export interface IExchangeCreate {
|
|
amount: number;
|
|
total: number;
|
|
playerId: number;
|
|
nickname: string;
|
|
balance: number;
|
|
telegram_id: string[] | number[];
|
|
shop_item?: number;
|
|
archive_request_id: number;
|
|
}
|
|
|
|
export interface IExchangeRequest {
|
|
id: number;
|
|
attributes: {
|
|
amount: number;
|
|
total: number;
|
|
player: { data: IPlayer };
|
|
roblox_nick: string;
|
|
status: 'done' | 'rejected' | 'pending';
|
|
};
|
|
}
|
|
|
|
export class ExchangeRequestApi {
|
|
private static instance: ExchangeRequestApi | null = null;
|
|
private httpInstance: AxiosInstance;
|
|
private httpBotInstance: AxiosInstance;
|
|
|
|
private constructor(token: string) {
|
|
this.httpInstance = HttpInstanceFactory.updateAuthorizedInstance(token);
|
|
this.httpBotInstance = axios.create({
|
|
baseURL: process.env.NEXT_PUBLIC_BOT_API,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
});
|
|
}
|
|
|
|
public static getInstance(token: string): ExchangeRequestApi {
|
|
if (this.instance) return this.instance;
|
|
this.instance = new ExchangeRequestApi(token);
|
|
return this.instance;
|
|
}
|
|
|
|
async createExchange(data: IExchangeCreate): Promise<IExchangeRequest> {
|
|
const res = (
|
|
await this.httpInstance.post<{ data: IExchangeRequest }>(
|
|
`/exchange-requests?populate=*`,
|
|
{
|
|
data: {
|
|
amount: toFixed(data.amount),
|
|
total: toFixed(data.total),
|
|
roblox_nick: data.nickname,
|
|
status: 'pending',
|
|
shop_item: data.shop_item ? data.shop_item : null,
|
|
},
|
|
},
|
|
)
|
|
).data.data;
|
|
if (res) {
|
|
await this.httpInstance.put(`/archive-requests/${data.archive_request_id}`, {
|
|
data: {
|
|
exchange_requests: {
|
|
connect: [res.id],
|
|
},
|
|
},
|
|
});
|
|
await this.httpInstance.put(`/players/${data.playerId}`, {
|
|
data: { balance: toFixed(data.balance - data.amount) },
|
|
});
|
|
await this.httpBotInstance.post(`/notify`, {
|
|
telegram_id: data.telegram_id,
|
|
exchange_id: res.id,
|
|
});
|
|
}
|
|
return res;
|
|
}
|
|
}
|