lefengyang
2026-08-20 d01a28cb030b2cb0ff1d42273c877a0f728519a6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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"
    };
  }
}