Files
doodle-mini/cloudfunctions/userLogin/index.js
T
2026-05-06 18:32:15 +08:00

85 lines
2.2 KiB
JavaScript

const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext();
const openid = wxContext.OPENID;
const unionid = wxContext.UNIONID || null;
const { action } = event;
switch (action) {
case 'updateProfile':
return await handleUpdateProfile(event, openid);
default:
return await handleSilentLogin(openid, unionid);
}
};
async function handleSilentLogin(openid, unionid) {
const usersCollection = db.collection('users');
const { data } = await usersCollection.where({ openid }).limit(1).get();
const now = db.serverDate();
if (data.length > 0) {
const user = data[0];
const updateData = { lastActiveAt: now };
if (unionid && !user.unionid) {
updateData.unionid = unionid;
}
await usersCollection.doc(user._id).update({ data: updateData });
return {
code: 0,
data: { ...user, ...updateData, lastActiveAt: new Date() },
};
} else {
const newUser = {
openid,
unionid,
nickName: null,
avatarUrl: null,
totalDownloads: 0,
createdAt: now,
lastActiveAt: now,
};
const { _id } = await usersCollection.add({ data: newUser });
return {
code: 0,
data: {
_id,
...newUser,
createdAt: new Date(),
lastActiveAt: new Date(),
},
};
}
}
async function handleUpdateProfile(event, openid) {
const { nickName, avatarUrl } = event;
const usersCollection = db.collection('users');
const { data } = await usersCollection.where({ openid }).limit(1).get();
if (data.length === 0) {
return { code: -1, message: '用户不存在' };
}
const updateData = {};
if (nickName !== undefined) updateData.nickName = nickName;
if (avatarUrl !== undefined) updateData.avatarUrl = avatarUrl;
await usersCollection.doc(data[0]._id).update({ data: updateData });
return {
code: 0,
data: { ...data[0], ...updateData },
};
}