49 lines
1.6 KiB
TypeScript
49 lines
1.6 KiB
TypeScript
import cloud from '@lafjs/cloud';
|
|
|
|
const db = cloud.database();
|
|
|
|
export default async function (ctx: FunctionContext) {
|
|
const body = ctx.body || {};
|
|
const { uid, token, type } = body;
|
|
if (typeof uid !== "string" || !uid.trim()) {
|
|
return { code: 0, data: null, msg: "未获取到有效uid" };
|
|
}
|
|
if (typeof token !== "string" || !token.trim()) {
|
|
return { code: 0, data: null, msg: "token校验失败" };
|
|
}
|
|
if (type !== "favorite" && type !== "desktop") {
|
|
return { code: 0, data: null, msg: "type必须为favorite或desktop" };
|
|
}
|
|
if (body.gameName === "iaa") {
|
|
return { code: 0, data: null, msg: "小程序福利仅支持主游戏" };
|
|
}
|
|
|
|
// 仅将指定项从未领取改为已领取;条件更新保证并发重试只有一次 changed=true。
|
|
const field = `miniProgramWelfare.${type}`;
|
|
const updated = await db.collection("users").where({
|
|
_id: uid,
|
|
token,
|
|
[field]: db.command.neq(true),
|
|
}).update({ [field]: true });
|
|
if (!updated || updated.ok === false || ![0, 1].includes(updated.updated)) {
|
|
return { code: 0, data: null, msg: "领取状态记录失败,请重试" };
|
|
}
|
|
|
|
const result = await db.collection("users").where({ _id: uid, token }).getOne();
|
|
if (!result.data) {
|
|
return { code: 0, data: null, msg: "用户不存在或token校验失败" };
|
|
}
|
|
const state = result.data.miniProgramWelfare;
|
|
return {
|
|
code: 1,
|
|
data: {
|
|
miniProgramWelfare: {
|
|
favorite: state?.favorite === true,
|
|
desktop: state?.desktop === true,
|
|
},
|
|
changed: updated.updated === 1,
|
|
},
|
|
msg: updated.updated === 1 ? "领取状态记录成功" : "已记录领取状态",
|
|
};
|
|
}
|