user.controller.ts56 lines, 1.5 KB
| 1 | import { userProxyService } from '@/services/user-proxy.service'; |
| 2 | import { getAuthenticatedUser } from '@/utils/auth'; |
| 3 | import { |
| 4 | createUserSchema, |
| 5 | SearchUsersQuery, |
| 6 | searchUsersQuerySchema, |
| 7 | userIdParamsSchema, |
| 8 | } from '@/validation/user.schema'; |
| 9 | import { AsyncHandler } from '@chatapp/common'; |
| 10 | |
| 11 | export const getUser: AsyncHandler = async (req, res, next) => { |
| 12 | try { |
| 13 | const { id } = userIdParamsSchema.parse(req.params); |
| 14 | const response = await userProxyService.getUserById(id); |
| 15 | res.json(response); |
| 16 | } catch (error) { |
| 17 | next(error); |
| 18 | } |
| 19 | }; |
| 20 | |
| 21 | export const getAllUsers: AsyncHandler = async (req, res, next) => { |
| 22 | try { |
| 23 | const response = await userProxyService.getAllUsers(); |
| 24 | res.json(response); |
| 25 | } catch (error) { |
| 26 | next(error); |
| 27 | } |
| 28 | }; |
| 29 | |
| 30 | export const createUser: AsyncHandler = async (req, res, next) => { |
| 31 | try { |
| 32 | const payload = createUserSchema.parse(req.body); |
| 33 | const response = await userProxyService.createUser(payload); |
| 34 | res.status(201).json(response); |
| 35 | } catch (error) { |
| 36 | next(error); |
| 37 | } |
| 38 | }; |
| 39 | |
| 40 | export const searchUsers: AsyncHandler = async (req, res, next) => { |
| 41 | try { |
| 42 | const user = getAuthenticatedUser(req); |
| 43 | const parsedQuery: SearchUsersQuery = searchUsersQuerySchema.parse(req.query); |
| 44 | const { query, limit, exclude } = parsedQuery; |
| 45 | const sanitizedExclude = Array.from(new Set([...exclude, user.id])); |
| 46 | |
| 47 | const users = await userProxyService.searchUsers({ |
| 48 | query, |
| 49 | limit, |
| 50 | exclude: sanitizedExclude, |
| 51 | }); |
| 52 | res.json({ data: users }); |
| 53 | } catch (error) { |
| 54 | next(error); |
| 55 | } |
| 56 | }; |