2024-11-25 11:08:54 +00:00

111 lines
2.5 KiB
TypeScript

import { LarkService } from "@egg/net-tool"
import { Context } from "../../types"
/**
* 处理登录请求
* @param req
* @returns
*/
const manageLogin = async (ctx: Context.Data) => {
const { req, genResp, logger, appMap, requestId } = ctx
logger.info("micro app login")
const url = new URL(req.url)
const code = url.searchParams.get("code")
const appName = url.searchParams.get("app_name")
if (!code) {
return genResp.badRequest("code not found")
}
if (!appName) {
return genResp.badRequest("app_name not found")
}
// 获取 app info
const appInfo = appMap[appName]
if (!appInfo) {
return genResp.badRequest("app not found")
}
const larkService = new LarkService({
appId: appInfo.app_id,
appSecret: appInfo.app_secret,
requestId,
})
const {
code: resCode,
data,
message,
} = await larkService.user.code2Login(code)
logger.debug(`get user session: ${JSON.stringify(data)}`)
if (resCode !== 0) {
return genResp.serverError(message)
}
return genResp.ok(data)
}
/**
* 处理批量获取用户信息请求
* @param req
* @returns
*/
const manageBatchUser = async (ctx: Context.Data) => {
const { body, genResp, logger, appMap, requestId } = ctx
logger.info("batch get user info")
if (!body) return genResp.badRequest("req body is empty")
const { user_ids, user_id_type, app_name } = body
if (!user_ids) {
return genResp.badRequest("user_ids not found")
}
if (!user_id_type) {
return genResp.badRequest("user_id_type not found")
}
if (!app_name) {
return genResp.badRequest("app_name not found")
}
// 获取 app info
const appInfo = appMap[app_name]
if (!appInfo) {
return genResp.badRequest("app not found")
}
const larkService = new LarkService({
appId: appInfo.app_id,
appSecret: appInfo.app_secret,
requestId,
})
const { code, data, message } = await larkService.user.batchGet(
user_ids,
user_id_type
)
logger.debug(`batch get user info: ${JSON.stringify(data)}`)
if (code !== 0) {
return genResp.serverError(message)
}
return genResp.ok(data)
}
/**
* 处理小程序请求
* @param req
* @returns
*/
export const manageMicroAppReq = async (ctx: Context.Data) => {
const path = ctx.path.child("/micro_app")
// 处理登录请求
if (path.exact("/login")) {
return manageLogin(ctx)
}
// 处理批量获取用户信息请求
if (path.exact("/batch_user")) {
return manageBatchUser(ctx)
}
return ctx.genResp.ok()
}