import { type FastifyReply, type FastifyRequest } from "fastify"; import type { IGetUserParams, IGetUserResponseError, IGetUserResponseSuccess, IPatchUserParams, IPatchUserRequest, IPatchUserResponseError, IPatchUserResponseSuccess, IGetSessionsParams, IGetSessionsResponseError, IGetSessionsResponseSuccess, } from "./types.js"; import { getUserByIdAuth, updateUserByIdAuth, getUserSessionsByIdAuth, } from "../../services/user/user.js"; import { API_ERROR } from "../errors.js"; const getUser = async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as IGetUserParams; const authHeader = request.headers["authorization"]; const user = await getUserByIdAuth(id, authHeader); if (!user) { reply.status(404); return { id: id, error: API_ERROR.NOT_FOUND, } as IGetUserResponseError; } if (user === API_ERROR.ACCESS_DENIED) { reply.status(403); return { id: id, error: API_ERROR.ACCESS_DENIED, } as IGetUserResponseError; } return { id: user.id, username: user.username, email: user.email, description: user.description, admin: user.admin, registerDate: user.registerDate.getTime(), lastLogin: user.lastLogin?.getTime() ?? 0, } as IGetUserResponseSuccess; }; const patchUser = async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as IPatchUserParams; const patchUserRequest = request.body as IPatchUserRequest; const authHeader = request.headers["authorization"]; const user = await updateUserByIdAuth(id, patchUserRequest, authHeader); if (!user) { reply.status(404); return { id: id, error: API_ERROR.NOT_FOUND, } as IPatchUserResponseError; } if (user === API_ERROR.ACCESS_DENIED) { reply.status(403); return { id: id, error: API_ERROR.ACCESS_DENIED, } as IPatchUserResponseError; } return { id: user.id, email: user.email, description: user.description, } as IPatchUserResponseSuccess; }; const getSessions = async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as IGetSessionsParams; const authHeader = request.headers["authorization"]; const sessions = await getUserSessionsByIdAuth(id, authHeader); if (!sessions) { reply.status(404); return { id: id, error: API_ERROR.NOT_FOUND, } as IGetSessionsResponseError; } if (sessions === API_ERROR.ACCESS_DENIED) { reply.status(403); return { id: id, error: API_ERROR.ACCESS_DENIED, } as IGetSessionsResponseError; } return { sessions: sessions.map((session) => ({ id: session.id, userId: session.userId, })), } as IGetSessionsResponseSuccess; }; export { getUser, patchUser, getSessions };