import {IBidTask} from "/src-com";
|
import {getStatusCodeError} from "../lib/getStatusCodeError";
|
|
/**
|
* submitBid函数的返回值接口
|
*/
|
export interface ISubmitBidResult {
|
status?: number;
|
responseText?: string;
|
isSuccess: boolean;
|
error?: string;
|
}
|
|
/**
|
* 提交出价请求的函数
|
* @param csrfToken CSRF令牌
|
* @param task 出价任务信息
|
* @returns 包含响应状态码、响应体文本、成功状态和错误说明的结果
|
*/
|
export async function submitBid(csrfToken: string, task: IBidTask): Promise<ISubmitBidResult> {
|
const { params } = task;
|
const itemId = params.goodsId;
|
const price = parseFloat(params.bid);
|
|
// 构建请求体
|
const requestBody = {
|
price,
|
quantity: 1,
|
isRegisterSNL: true,
|
isAcceptAuth: false,
|
isBuyNow: task.type === 'buyItNow',
|
isPartial: false,
|
withOutBidNotice: false
|
};
|
|
const response = await fetch(
|
`https://auctions.yahoo.co.jp/api/bid/v1/items/${itemId}/bid`,
|
{
|
headers: {
|
accept: "application/json",
|
"content-type": "application/json",
|
"x-csrf-token": csrfToken
|
},
|
body: JSON.stringify(requestBody),
|
method: "POST"
|
}
|
);
|
// 读取响应体文本
|
const responseText = await response.text();
|
|
// 判断请求是否成功(状态码在200-300之间)
|
let isSuccess = response.ok;
|
|
if(isSuccess) {
|
return {
|
status: response.status,
|
responseText,
|
isSuccess
|
}
|
}
|
|
let error = "";
|
|
try {
|
// 尝试解析响应体为JSON对象
|
const responseJson = JSON.parse(responseText);
|
|
// 检查是否包含nextBidPrice字段
|
if (responseJson.nextBidPrice && price < responseJson.nextBidPrice) {
|
// 设置为失败状态
|
isSuccess = false;
|
// 构建错误信息,包含当前出价和允许的最低价
|
error = `Bid price ${price} is lower than the minimum allowed price ${responseJson.nextBidPrice}`;
|
} else if (!isSuccess) {
|
// 原有的错误处理逻辑
|
const statusError = getStatusCodeError(response.status);
|
error = [statusError, responseText].filter(Boolean).join(" - ");
|
}
|
} catch (e) {
|
// 如果解析JSON失败,使用原有的错误处理逻辑
|
if (!isSuccess) {
|
const statusError = getStatusCodeError(response.status);
|
error = [statusError, responseText].filter(Boolean).join(" - ");
|
}
|
}
|
|
return {
|
status: response.status,
|
responseText,
|
isSuccess,
|
error
|
};
|
}
|