cb/server/laf-cloud/functions/getTransfer.ts
2026-08-20 19:27:58 +08:00

87 lines
2.2 KiB
TypeScript

import cloud from '@lafjs/cloud';
import Utils from "@/Utils";
const db = cloud.database();
type Transfer = {
isXxwz: boolean;
time: number;
};
export default async function (ctx: FunctionContext) {
const uid = ctx.body.uid;
const action = ctx.body.action;
if (!uid) {
return { code: 0, data: null, msg: "未获取到uid" };
}
if (action !== "read" && action !== "save") {
return { code: 0, data: null, msg: "action必须为read或save" };
}
const dbname = ctx.body.gameName == "iaa" ? "usersAd" : "users";
const user = await db.collection(dbname).where({ _id: uid }).getOne();
if (!user.data) {
return { code: 0, data: null, msg: "未获取到玩家数据" };
}
if (user.data.token && !Utils.checkToken(ctx.body.token, user.data.token)) {
return { code: 0, data: null, msg: "token校验失败" };
}
const transfer = normalizeTransfer(user.data.transfer);
if (action === "read") {
return {
code: 1,
data: { transfer, changed: false },
msg: "获取转移状态成功"
};
}
if (transfer.isXxwz) {
return {
code: 1,
data: { transfer, changed: false },
msg: "转移状态已确认"
};
}
const nextTransfer: Transfer = {
isXxwz: true,
time: Date.now()
};
const result = await db.collection(dbname)
.where({ _id: uid, "transfer.isXxwz": db.command.neq(true) })
.update({ transfer: nextTransfer });
if (result.updated === 1) {
return {
code: 1,
data: { transfer: nextTransfer, changed: true },
msg: "转移状态更新成功"
};
}
// 并发请求可能已经先完成更新,重新读取以返回首次写入的时间。
const latestUser = await db.collection(dbname).where({ _id: uid }).getOne();
const latestTransfer = normalizeTransfer(latestUser.data?.transfer);
if (latestTransfer.isXxwz) {
return {
code: 1,
data: { transfer: latestTransfer, changed: false },
msg: "转移状态已确认"
};
}
return { code: 0, data: null, msg: "转移状态更新失败" };
}
function normalizeTransfer(transfer: any): Transfer {
if (transfer?.isXxwz !== true) {
return { isXxwz: false, time: 0 };
}
return {
isXxwz: true,
time: Number(transfer.time) || 0
};
}