| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
- import { z } from '@hono/zod-openapi';
- import { WechatAuthService } from '@/server/modules/wechat/wechat-auth.service';
- import { ErrorSchema } from '@/server/utils/errorHandler';
- import { AppDataSource } from '@/server/data-source';
- import { UserService } from '@/server/modules/users/user.service';
- import { AuthService } from '@/server/modules/auth/auth.service';
- import { UserSchema } from '@/server/modules/users/user.schema';
- import { authMiddleware } from '@/server/middleware/auth.middleware';
- import { AuthContext } from '@/server/types/context';
- import { parseWithAwait } from '@/server/utils/parseWithAwait';
- const BindWechatSchema = z.object({
- code: z.string().min(1).openapi({
- example: '0816TxlL1Qe3QY0qgDlL1pQxlL16TxlO',
- description: '微信授权code'
- })
- });
- const userService = new UserService(AppDataSource);
- const authService = new AuthService(userService);
- const wechatAuthService = new WechatAuthService(userService, authService);
- const bindWechatRoute = createRoute({
- method: 'post',
- path: '/bind',
- middleware: [authMiddleware],
- request: {
- body: {
- content: {
- 'application/json': {
- schema: BindWechatSchema
- }
- }
- }
- },
- responses: {
- 200: {
- description: '绑定微信账号成功',
- content: {
- 'application/json': {
- schema: UserSchema
- }
- }
- },
- 400: {
- description: '请求参数错误',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- },
- 401: {
- description: '认证失败',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- }
- }
- });
- const app = new OpenAPIHono<AuthContext>().openapi(bindWechatRoute, async (c) => {
- try {
- const user = c.get('user');
- const { code } = await c.req.json();
- const result = await wechatAuthService.bindWechatToUser(user.id, code);
-
- // 使用 parseWithAwait 确保返回数据符合Schema定义
- const validatedResult = await parseWithAwait(UserSchema, result);
-
- return c.json(validatedResult, 200);
- } catch (error) {
- return c.json({
- code: 400,
- message: error instanceof Error ? error.message : '绑定微信账号失败'
- }, 400);
- }
- });
- export default app;
|