routes_users.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import { Hono } from 'hono'
  2. import type { Variables } from './app.tsx'
  3. import type { WithAuth } from './app.tsx'
  4. export function createUserRoutes(withAuth: WithAuth) {
  5. const usersRoutes = new Hono<{ Variables: Variables }>()
  6. // 获取用户列表
  7. usersRoutes.get('/', withAuth, async (c) => {
  8. try {
  9. const apiClient = c.get('apiClient')
  10. const page = Number(c.req.query('page')) || 1
  11. const pageSize = Number(c.req.query('pageSize')) || 10
  12. const offset = (page - 1) * pageSize
  13. const search = c.req.query('search') || ''
  14. let query = apiClient.database.table('users')
  15. .orderBy('id', 'desc')
  16. if (search) {
  17. query = query.where((builder) => {
  18. builder.where('username', 'like', `%${search}%`)
  19. .orWhere('nickname', 'like', `%${search}%`)
  20. .orWhere('email', 'like', `%${search}%`)
  21. })
  22. }
  23. const total = await query.clone().count()
  24. const users = await query.select('id', 'username', 'nickname', 'email', 'phone', 'role', 'created_at')
  25. .limit(pageSize).offset(offset)
  26. return c.json({
  27. data: users,
  28. pagination: {
  29. total: Number(total),
  30. current: page,
  31. pageSize
  32. }
  33. })
  34. } catch (error) {
  35. console.error('获取用户列表失败:', error)
  36. return c.json({ error: '获取用户列表失败' }, 500)
  37. }
  38. })
  39. // 获取单个用户详情
  40. usersRoutes.get('/:id', withAuth, async (c) => {
  41. try {
  42. const id = Number(c.req.param('id'))
  43. if (!id || isNaN(id)) {
  44. return c.json({ error: '无效的用户ID' }, 400)
  45. }
  46. const apiClient = c.get('apiClient')
  47. const user = await apiClient.database.table('users')
  48. .where('id', id)
  49. .select('id', 'username', 'nickname', 'email', 'phone', 'role', 'created_at')
  50. .first()
  51. if (!user) {
  52. return c.json({ error: '用户不存在' }, 404)
  53. }
  54. return c.json({
  55. data: user,
  56. message: '获取用户详情成功'
  57. })
  58. } catch (error) {
  59. console.error('获取用户详情失败:', error)
  60. return c.json({ error: '获取用户详情失败' }, 500)
  61. }
  62. })
  63. // 创建用户
  64. usersRoutes.post('/', withAuth, async (c) => {
  65. try {
  66. const apiClient = c.get('apiClient')
  67. const body = await c.req.json()
  68. // 验证必填字段
  69. const { username, nickname, email, password, role } = body
  70. if (!username || !nickname || !email || !password || !role) {
  71. return c.json({ error: '缺少必要的用户信息' }, 400)
  72. }
  73. // 检查用户名是否已存在
  74. const existingUser = await apiClient.database.table('users')
  75. .where('username', username)
  76. .first()
  77. if (existingUser) {
  78. return c.json({ error: '用户名已存在' }, 400)
  79. }
  80. // 创建用户
  81. const [id] = await apiClient.database.table('users').insert({
  82. username,
  83. nickname,
  84. email,
  85. password: password, // 加密密码
  86. role,
  87. created_at: new Date(),
  88. updated_at: new Date()
  89. })
  90. const newUser = await apiClient.database.table('users')
  91. .where('id', id)
  92. .select('id', 'username', 'nickname', 'email', 'role', 'created_at')
  93. .first()
  94. return c.json({
  95. data: newUser,
  96. message: '创建用户成功'
  97. })
  98. } catch (error) {
  99. console.error('创建用户失败:', error)
  100. return c.json({ error: '创建用户失败' }, 500)
  101. }
  102. })
  103. // 更新用户
  104. usersRoutes.put('/:id', withAuth, async (c) => {
  105. try {
  106. const id = Number(c.req.param('id'))
  107. if (!id || isNaN(id)) {
  108. return c.json({ error: '无效的用户ID' }, 400)
  109. }
  110. const apiClient = c.get('apiClient')
  111. const body = await c.req.json()
  112. // 验证必填字段
  113. const { username, nickname, email, role } = body
  114. if (!username || !nickname || !email || !role) {
  115. return c.json({ error: '缺少必要的用户信息' }, 400)
  116. }
  117. // 检查用户是否存在
  118. const existingUser = await apiClient.database.table('users')
  119. .where('id', id)
  120. .first()
  121. if (!existingUser) {
  122. return c.json({ error: '用户不存在' }, 404)
  123. }
  124. // 如果修改了用户名,检查新用户名是否已被使用
  125. if (username !== existingUser.username) {
  126. const userWithSameName = await apiClient.database.table('users')
  127. .where('username', username)
  128. .whereNot('id', id.toString())
  129. .first()
  130. if (userWithSameName) {
  131. return c.json({ error: '用户名已存在' }, 400)
  132. }
  133. }
  134. // 更新用户信息
  135. const updateData: any = {
  136. username,
  137. nickname,
  138. email,
  139. role,
  140. updated_at: new Date()
  141. }
  142. // 如果提供了新密码,则更新密码
  143. if (body.password) {
  144. updateData.password = body.password
  145. }
  146. await apiClient.database.table('users')
  147. .where('id', id)
  148. .update(updateData)
  149. const updatedUser = await apiClient.database.table('users')
  150. .where('id', id)
  151. .select('id', 'username', 'nickname', 'email', 'role', 'created_at')
  152. .first()
  153. return c.json({
  154. data: updatedUser,
  155. message: '更新用户成功'
  156. })
  157. } catch (error) {
  158. console.error('更新用户失败:', error)
  159. return c.json({ error: '更新用户失败' }, 500)
  160. }
  161. })
  162. // 删除用户
  163. usersRoutes.delete('/:id', withAuth, async (c) => {
  164. try {
  165. const id = Number(c.req.param('id'))
  166. if (!id || isNaN(id)) {
  167. return c.json({ error: '无效的用户ID' }, 400)
  168. }
  169. const apiClient = c.get('apiClient')
  170. // 检查用户是否存在
  171. const existingUser = await apiClient.database.table('users')
  172. .where('id', id)
  173. .first()
  174. if (!existingUser) {
  175. return c.json({ error: '用户不存在' }, 404)
  176. }
  177. // 检查是否为最后一个管理员
  178. if (existingUser.role === 'admin') {
  179. const adminCount = await apiClient.database.table('users')
  180. .where('role', 'admin')
  181. .count()
  182. if (Number(adminCount) <= 1) {
  183. return c.json({ error: '不能删除最后一个管理员' }, 400)
  184. }
  185. }
  186. // 删除用户
  187. await apiClient.database.table('users')
  188. .where('id', id)
  189. .delete()
  190. return c.json({
  191. message: '删除用户成功',
  192. id
  193. })
  194. } catch (error) {
  195. console.error('删除用户失败:', error)
  196. return c.json({ error: '删除用户失败' }, 500)
  197. }
  198. })
  199. return usersRoutes
  200. }