| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
- import { UserService } from '../../modules/users/user.service';
- import { z } from '@hono/zod-openapi';
- import { authMiddleware } from '../../middleware/auth.middleware';
- import { ErrorSchema } from '../../utils/errorHandler';
- import { AppDataSource } from '../../data-source';
- import { AuthContext } from '../../types/context';
- import { UserSchema } from '@/server/modules/users/user.entity';
- const userService = new UserService(AppDataSource);
- const CreateUserSchema = UserSchema.omit({
- id: true,
- createdAt: true,
- updatedAt: true,
- roles: true,
- defaultDepartmentId: true,
- dataScopeType: true,
- }).extend({
- phone: UserSchema.shape.phone.optional(),
- email: UserSchema.shape.email.optional(),
- nickname: UserSchema.shape.nickname.optional(),
- name: UserSchema.shape.name.optional(),
- avatar: UserSchema.shape.avatar.optional(),
- roleIds: z.array(z.number().int().positive()).optional().openapi({
- description: '角色ID列表',
- example: [1, 2]
- }),
- defaultDepartmentId: z.number().int().positive().optional().openapi({
- description: '默认部门ID',
- example: 1
- }),
- dataScopeType: z.enum(['PERSONAL', 'DEPARTMENT', 'SUB_DEPARTMENT', 'COMPANY', 'CUSTOM']).optional().openapi({
- description: '数据范围类型',
- example: 'PERSONAL'
- }),
- })
- const createUserRoute = createRoute({
- method: 'post',
- path: '/',
- middleware: authMiddleware,
- request: {
- body: {
- content: {
- 'application/json': {
- schema: CreateUserSchema
- }
- }
- }
- },
- responses: {
- 201: {
- description: '创建成功',
- content: {
- 'application/json': {
- schema: UserSchema
- }
- }
- },
- 400: {
- description: '输入数据无效',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- },
- 500: {
- description: '服务器错误',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- }
- }
- });
- const app = new OpenAPIHono<AuthContext>().openapi(createUserRoute, async (c) => {
- try {
- const data = c.req.valid('json');
- const { roleIds, ...userData } = data;
-
- // 创建用户
- const user = await userService.createUser(userData);
-
- // 分配角色
- if (roleIds && roleIds.length > 0) {
- await userService.assignRoles(user.id, roleIds);
- }
-
- // 重新获取用户(包含角色信息)
- const userWithRoles = await userService.getUserById(user.id);
- return c.json(userWithRoles, 201);
- } catch (error) {
- const message = error instanceof Error ? error.message : '服务器错误';
- return c.json({ code: 500, message }, 500);
- }
- });
- export default app;
|