72 lines
1.9 KiB
JavaScript
72 lines
1.9 KiB
JavaScript
function json(data, status = 200) {
|
|
return new Response(JSON.stringify(data), {
|
|
status,
|
|
headers: { "content-type": "application/json; charset=UTF-8" },
|
|
});
|
|
}
|
|
|
|
function toInt(v, d) {
|
|
const n = Number(v);
|
|
return Number.isFinite(n) && n > 0 ? Math.floor(n) : d;
|
|
}
|
|
|
|
export async function onRequestGet(context) {
|
|
const db = context.env.DB;
|
|
if (!db) {
|
|
return json({ success: false, error: "缺少 D1 绑定 DB" }, 500);
|
|
}
|
|
|
|
try {
|
|
const url = new URL(context.request.url);
|
|
const page = toInt(url.searchParams.get("page"), 1);
|
|
const limit = Math.min(100, toInt(url.searchParams.get("limit"), 10));
|
|
const month = (url.searchParams.get("month") || "").trim();
|
|
const day = (url.searchParams.get("day") || "").trim();
|
|
const offset = (page - 1) * limit;
|
|
|
|
const where = ["1=1"];
|
|
const params = [];
|
|
|
|
// 时间字段是 YYYY-MM-DD HH:MM:SS 文本,直接前缀过滤可走索引/减少转换成本
|
|
if (month) {
|
|
where.push("timestamp LIKE ?");
|
|
params.push(`${month}%`);
|
|
}
|
|
if (day) {
|
|
where.push("timestamp LIKE ?");
|
|
params.push(`${day}%`);
|
|
}
|
|
|
|
const whereSql = where.join(" AND ");
|
|
const dataSql = `
|
|
SELECT *
|
|
FROM backup_trades
|
|
WHERE ${whereSql}
|
|
ORDER BY timestamp DESC
|
|
LIMIT ? OFFSET ?
|
|
`;
|
|
const countSql = `
|
|
SELECT COUNT(*) AS cnt
|
|
FROM backup_trades
|
|
WHERE ${whereSql}
|
|
`;
|
|
|
|
const dataResult = await db.prepare(dataSql).bind(...params, limit, offset).all();
|
|
const countResult = await db.prepare(countSql).bind(...params).first();
|
|
|
|
const total = Number(countResult?.cnt || 0);
|
|
const totalPages = total > 0 ? Math.ceil(total / limit) : 1;
|
|
|
|
return json({
|
|
success: true,
|
|
data: dataResult.results || [],
|
|
page,
|
|
limit,
|
|
total,
|
|
total_pages: totalPages,
|
|
});
|
|
} catch (error) {
|
|
return json({ success: false, error: String(error) }, 500);
|
|
}
|
|
}
|