/
foult080
/
college-schedule-app
Обзор
Документация
Войти
/
foult080
/
college-schedule-app
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/controllers/groups.controller.ts
154 строки
5 KB
Foult080
feat(api): update api and tests
06 июл 2026, 12:54
06 июл 2026, 12:54
6f27c7e
Код
Авторство
О чём код?
import { NextFunction, Request, Response } from 'express'; import { DatabaseHelper } from '../utils/database.js'; import { BadRequestError, ConflictError, NotFoundError, } from '../utils/http-errors.js'; import { IGroup, ICreateGroupDto, IUpdateGroupDto } from '../types/types.js'; /** * Get all groups * GET /api/groups */ export const getAllGroups = async (_req: Request, res: Response, next: NextFunction): Promise<void> => { try { const result = await DatabaseHelper.select<IGroup>('groups', ['id', 'name', 'leader_name', 'leader_phone']); res.status(200).json(result.rows); } catch (error) { next(error); } }; /** * Get group by ID * GET /api/groups/:id */ export const getGroupById = async (req: Request, res: Response, next: NextFunction): Promise<void> => { try { const { id } = req.params; const groupId = parseInt(id as string, 10); if (isNaN(groupId) || groupId <= 0) { throw new BadRequestError('Invalid group ID'); } const result = await DatabaseHelper.select<IGroup>('groups', ['id', 'name', 'leader_name', 'leader_phone'], { id: groupId }); if (result.rows.length === 0) { throw new NotFoundError('Group not found'); } res.status(200).json(result.rows[0]); } catch (error) { next(error); } }; /** * Create new group * POST /api/groups */ export const createGroup = async (req: Request, res: Response, next: NextFunction): Promise<void> => { try { const { name, leader_name, leader_phone }: ICreateGroupDto = req.body; // Validation if (!name) { throw new BadRequestError('Group name is required'); } if (name.length > 50) { throw new BadRequestError('Group name must be less than 50 characters'); } // Check if group name already exists const existingGroup = (await DatabaseHelper.select('groups', ['id'], { name })).rows[0]; if (existingGroup) { throw new ConflictError('Group with this name already exists'); } const newGroupData: Record<string, unknown> = { name }; if (leader_name !== undefined) newGroupData.leader_name = leader_name; if (leader_phone !== undefined) newGroupData.leader_phone = leader_phone; const result = await DatabaseHelper.insert<IGroup>('groups', newGroupData, ['id', 'name', 'leader_name', 'leader_phone']); res.status(201).json(result.rows[0]); } catch (error) { next(error); } }; /** * Update group by ID * PUT /api/groups/:id */ export const updateGroup = async (req: Request, res: Response, next: NextFunction): Promise<void> => { try { const { id } = req.params; const { name, leader_name, leader_phone }: IUpdateGroupDto = req.body; const groupId = parseInt(id as string, 10); if (isNaN(groupId)) { throw new BadRequestError('Invalid group ID'); } // Check if group exists const existingGroup = (await DatabaseHelper.select('groups', ['id', 'name'], { id: groupId })).rows[0]; if (!existingGroup) { throw new NotFoundError('Group not found'); } // Validation if (name !== undefined && name.length > 50) { throw new BadRequestError('Group name must be less than 50 characters'); } // Check if new name already exists (if name is being changed) if (name && name !== existingGroup.name) { const nameExists = (await DatabaseHelper.select('groups', ['id'], { name })).rows[0]; if (nameExists) { throw new ConflictError('Group with this name already exists'); } } const updateData: Record<string, unknown> = {}; if (name !== undefined) updateData.name = name; if (leader_name !== undefined) updateData.leader_name = leader_name; if (leader_phone !== undefined) updateData.leader_phone = leader_phone; const result = await DatabaseHelper.update<IGroup>('groups', updateData, { id: groupId }, ['id', 'name', 'leader_name', 'leader_phone']); res.status(200).json(result.rows[0]); } catch (error) { next(error); } }; /** * Delete group by ID * DELETE /api/groups/:id */ export const deleteGroup = async (req: Request, res: Response, next: NextFunction): Promise<void> => { try { const { id } = req.params; const groupId = parseInt(id as string, 10); if (isNaN(groupId)) { throw new BadRequestError('Invalid group ID'); } // Check if group exists const existingGroup = (await DatabaseHelper.select('groups', ['id'], { id: groupId })).rows[0]; if (!existingGroup) { throw new NotFoundError('Group not found'); } await DatabaseHelper.delete('groups', { id: groupId }); res.status(204).send(); } catch (error) { if (error instanceof Error && error.message.includes('foreign key')) { throw new ConflictError('Cannot delete group: it is referenced by schedules'); } next(error); } };