| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
- import { z } from '@hono/zod-openapi';
- import { MiniAuthService } from '../services';
- import { AppDataSource } from '@d8d/shared-utils';
- import { ErrorSchema } from '@d8d/shared-utils';
- import { UserEntity } from '@d8d/user-module';
- import { MiniLoginSchema, MiniLoginResponseSchema } from '../schemas';
- const miniLoginRoute = createRoute({
- method: 'post',
- path: '/mini-login',
- request: {
- body: {
- content: {
- 'application/json': {
- schema: MiniLoginSchema
- }
- }
- }
- },
- responses: {
- 200: {
- description: '小程序登录成功',
- content: {
- 'application/json': {
- schema: MiniLoginResponseSchema
- }
- }
- },
- 400: {
- description: '参数错误',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- },
- 500: {
- description: '服务器错误',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- }
- }
- });
- const app = new OpenAPIHono().openapi(miniLoginRoute, async (c) => {
- try {
- // 在路由处理函数内部初始化服务
- const miniAuthService = new MiniAuthService(AppDataSource);
- const { code, userInfo } = c.req.valid('json');
- const result = await miniAuthService.miniLogin(code);
- // 如果有用户信息,更新用户资料
- if (userInfo) {
- await miniAuthService.updateUserProfile(result.user.id, {
- nickname: userInfo.nickName,
- avatarUrl: userInfo.avatarUrl
- });
- // 重新获取更新后的用户信息
- const updatedUser = await AppDataSource.getRepository(UserEntity).findOne({
- where: { id: result.user.id },
- relations: ['avatarFile']
- });
- if (updatedUser) {
- result.user = updatedUser;
- }
- }
- return c.json({
- token: result.token,
- user: {
- id: result.user.id,
- username: result.user.username,
- nickname: result.user.nickname,
- phone: result.user.phone,
- email: result.user.email,
- avatarFileId: result.user.avatarFileId,
- registrationSource: result.user.registrationSource
- },
- isNewUser: result.isNewUser
- }, 200);
- } catch (error) {
- const { code = 500, message = '登录失败' } = error as Error & { code?: number };
- return c.json({ code, message }, 500);
- }
- });
- export default app;
|