82 lines
1.9 KiB
TypeScript
82 lines
1.9 KiB
TypeScript
import { RecordModel } from "pocketbase"
|
||
|
||
import { Context } from "../../types"
|
||
import { managePbError } from "../../utils/pbTools"
|
||
import pbClient from "../pbClient"
|
||
|
||
// 用户接口定义
|
||
interface User {
|
||
email: string
|
||
name: string
|
||
openId: string
|
||
userId: string
|
||
avatar: string
|
||
password: string
|
||
emailVisibility: boolean
|
||
verified: boolean
|
||
}
|
||
|
||
// 用户模型类型
|
||
export type UserModel = User & RecordModel
|
||
|
||
/**
|
||
* 创建用户
|
||
* @param {User} user - 用户信息
|
||
* @returns {Promise<UserModel>} - 创建的用户模型
|
||
*/
|
||
const create = async (user: User) =>
|
||
managePbError<UserModel>(() => pbClient.collection("user").create(user))
|
||
|
||
/**
|
||
* 通过用户ID获取用户
|
||
* @param {string} userId - 用户ID
|
||
* @returns {Promise<UserModel | null>} - 用户模型或null
|
||
*/
|
||
const getByUserId = async (userId: string) =>
|
||
managePbError<UserModel>(() =>
|
||
pbClient.collection("user").getFirstListItem(`user_id = "${userId}"`)
|
||
)
|
||
|
||
/**
|
||
* 通过上下文获取用户
|
||
* @param {Context} context - 上下文对象
|
||
* @returns {Promise<UserModel | null>} - 用户模型或null
|
||
*/
|
||
const getByCtx = async ({ larkBody, larkService }: Context) => {
|
||
if (!larkBody.userId) return null
|
||
// 先从数据库获取用户信息
|
||
const user = await getByUserId(larkBody.userId)
|
||
if (user) return user
|
||
// 如果数据库中没有用户信息,从larkService获取用户信息
|
||
const userInfo = await larkService.user.getOne(larkBody.userId, "user_id")
|
||
if (userInfo.code !== 0) return null
|
||
// 解构用户信息
|
||
const {
|
||
user_id,
|
||
open_id,
|
||
avatar: { avatar_origin },
|
||
email,
|
||
name,
|
||
} = userInfo.data.user
|
||
const newUser = {
|
||
userId: user_id,
|
||
openId: open_id,
|
||
avatar: avatar_origin,
|
||
email,
|
||
name,
|
||
emailVisibility: false,
|
||
verified: false,
|
||
password: email,
|
||
}
|
||
// 创建新用户
|
||
const finalUser = await create(newUser)
|
||
return finalUser
|
||
}
|
||
|
||
// 用户对象
|
||
const user = {
|
||
getByCtx,
|
||
}
|
||
|
||
export default user
|