Files
doodle-mini/cloudfunctions/userLogin/index.js
T

100 lines
2.8 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);
}
};
function serializeUser(user) {
return {
...user,
createdAt:
user.createdAt instanceof Date
? user.createdAt
: user.createdAt?.toDate?.() || user.createdAt || null,
lastActiveAt:
user.lastActiveAt instanceof Date
? user.lastActiveAt
: user.lastActiveAt?.toDate?.() || user.lastActiveAt || null,
};
}
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 });
const latest = (
await usersCollection.doc(user._id).get()
).data;
return {
code: 0,
data: serializeUser(latest),
};
} else {
const newUser = {
openid,
unionid,
nickName: null,
avatarUrl: null,
totalDownloads: 0,
createdAt: now,
lastActiveAt: now,
};
const { _id } = await usersCollection.add({ data: newUser });
const latest = (await usersCollection.doc(_id).get()).data;
return {
code: 0,
data: serializeUser(latest),
};
}
}
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;
updateData.lastActiveAt = db.serverDate();
await usersCollection.doc(data[0]._id).update({ data: updateData });
const latest = (await usersCollection.doc(data[0]._id).get()).data;
return {
code: 0,
data: serializeUser(latest),
};
}