import {IBidTask} from "/src-com";
|
import {getStatusCodeError} from "../lib/getStatusCodeError";
|
|
/**
|
* generateBidPreview函数的返回值接口
|
*/
|
export interface IGenerateBidPreviewResult {
|
status: number;
|
csrfToken: string;
|
body: any | null;
|
isSuccess: boolean;
|
error: string;
|
}
|
|
/**
|
* 生成出价预览请求的函数
|
* @param task 出价任务信息
|
* @returns 包含响应状态码、x-csrf-token、响应体对象、成功状态和错误信息的结果
|
*/
|
export async function generateBidPreview(task: IBidTask): Promise<IGenerateBidPreviewResult> {
|
const { params, type } = task;
|
const itemId = params.goodsId;
|
const price = parseFloat(params.bid);
|
const isBuyNow = type === 'buyItNow';
|
|
let response;
|
try {
|
response = await fetch(
|
`https://auctions.yahoo.co.jp/api/bid/v1/items/${itemId}/bid/preview?price=${price}&quantity=1&isPartial=false&isBuyNow=${isBuyNow}&enableOutBidNotice=false`,
|
{
|
headers: {
|
accept: "application/json",
|
},
|
method: "GET",
|
}
|
);
|
|
// 提取x-csrf-token
|
const csrfToken = response.headers.get("x-csrf-token") || "";
|
|
// 判断请求是否成功(状态码在200-300之间)
|
let isSuccess = response.ok;
|
|
let body = null;
|
let error = "";
|
|
if (isSuccess) {
|
// 解析响应体为JSON对象
|
body = await response.json();
|
// 检查是否包含nextBidPrice字段
|
if (body.nextBidPrice && price < body.nextBidPrice) {
|
// 设置为失败状态
|
isSuccess = false;
|
// 构建错误信息
|
error = `Bid price ${price} is lower than the minimum allowed price ${body.nextBidPrice}`;
|
}
|
} else {
|
// 读取响应体文本
|
const responseText = await response.text();
|
// 构建错误信息
|
const statusError = getStatusCodeError(response.status);
|
const errorParts = [statusError, responseText].filter(Boolean);
|
error = errorParts.join(" - ");
|
}
|
|
return {
|
status: response.status,
|
csrfToken,
|
body,
|
isSuccess,
|
error
|
};
|
} catch (err) {
|
// 处理网络错误或其他异常
|
return {
|
status: 0,
|
csrfToken: "",
|
body: null,
|
isSuccess: false,
|
error: err instanceof Error ? err.message : "Unknown error"
|
};
|
}
|
}
|