60 lines
1.7 KiB
JavaScript
60 lines
1.7 KiB
JavaScript
const cloud = require('wx-server-sdk')
|
|
|
|
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
|
|
const db = cloud.database()
|
|
|
|
// Generate a unique handle from openid
|
|
function makeHandle(openid) {
|
|
const suffix = openid.slice(-6).toLowerCase()
|
|
return `@user_${suffix}`
|
|
}
|
|
|
|
// Default avatar pool to randomise new user avatars
|
|
const AVATAR_KEYS = [
|
|
'gradient-avatar-1', 'gradient-avatar-2', 'gradient-avatar-3',
|
|
'gradient-avatar-4', 'gradient-avatar-5', 'gradient-avatar-6'
|
|
]
|
|
|
|
exports.main = async event => {
|
|
const { OPENID } = cloud.getWXContext()
|
|
if (!OPENID) throw new Error('no openid in wx context')
|
|
|
|
const now = Date.now()
|
|
const existed = await db.collection('users').where({ openid: OPENID }).limit(1).get()
|
|
|
|
if (existed.data.length) {
|
|
const user = existed.data[0]
|
|
await db.collection('users').doc(user._id).update({
|
|
data: { lastLoginAt: now }
|
|
})
|
|
return {
|
|
openid: OPENID,
|
|
user: { ...user, lastLoginAt: now },
|
|
isNew: false
|
|
}
|
|
}
|
|
|
|
// New user — create with sensible defaults
|
|
const avatarKey = AVATAR_KEYS[Math.floor(Math.random() * AVATAR_KEYS.length)]
|
|
const user = {
|
|
openid: OPENID,
|
|
nickname: event.userInfo?.nickname || '宠物达人',
|
|
handle: makeHandle(OPENID),
|
|
avatarKey,
|
|
avatarUrl: '',
|
|
profileCompleted: false,
|
|
location: '',
|
|
yearsWithPets: 0,
|
|
level: 1,
|
|
bio: '',
|
|
verified: false,
|
|
stats: { posts: 0, following: 0, followers: 0, favorites: 0 },
|
|
preferences: { notifications: true, nearbyVisible: true },
|
|
createdAt: now,
|
|
lastLoginAt: now
|
|
}
|
|
|
|
const result = await db.collection('users').add({ data: user })
|
|
return { openid: OPENID, user: { _id: result._id, ...user }, isNew: true }
|
|
}
|