2026-07-27 11:28:33 +08:00

73 lines
1.9 KiB
JavaScript

const { generateRandomString } = require("../../common");
const dayjs = require("dayjs");
let db = null;
exports.main = async (event, mongodb) => {
db = mongodb;
switch (event.type) {
case "getCorpCache":
return await this.getCorpCache(event);
case "createCorpCache":
return await this.createCorpCache(event);
}
};
exports.getCorpCache = async (item) => {
const { corpId, cacheType } = item;
const collection = db.collection("corp-cache");
// 查询符合条件的数据
const obj = await collection.findOne({ corpId, cacheType });
if (!obj) {
return { success: false, data: null };
}
// 计算expiresTime与当前时间的差值
const diffInSeconds = obj.expiresTime - dayjs().valueOf();
return {
success: diffInSeconds > 1800 * 1000, // 判断expiresTime是否大于30分钟
data: obj,
};
};
exports.createCorpCache = async (item) => {
try {
const { corpId, cacheType, value, expiresIn, id } = item;
const collection = db.collection("corp-cache");
const currentTime = dayjs().valueOf();
const expiresTime = dayjs().add(expiresIn, "second").valueOf();
let res;
if (id) {
// 更新现有文档
res = await collection.updateOne(
{ _id: id },
{
$set: {
update: currentTime,
expiresTime,
value,
},
}
);
} else {
// 插入新文档
res = await collection.insertOne({
corpId,
cacheType,
value,
createTime: currentTime,
expiresTime,
expiresIn,
_id: generateRandomString(24),
});
}
return {
success: true,
message: "操作成功",
res,
};
} catch (error) {
console.error("Create Corp Cache Error:", error);
return {
success: false,
message: "操作失败,请稍后重试",
error: error.message || error,
};
}
};