import db from '../db.js'; import customError from '../response/customError.js'; import responseCodes from '../response/responseCodes.js'; import errorHandler from '../utils/pgerrorhandler.js'; class GroupService { async create(name, creatorId) { let res = await db.query("INSERT INTO groups (name, admin_id) VALUES ($1, $2) RETURNING ID", [name, creatorId]).catch((e) => errorHandler(e, "groups")); return res.rows[0]; } async getById(id) { let res = (await db.query("SELECT * FROM groups WHERE id = $1", [id])); if (res.rowCount == 0) throw new customError(`getById group not found`, responseCodes.responses.groups.id_not_found); return res.rows[0]; } async getAdminId(id) { return (await db.query("SELECT admin_id FROM groups WHERE ID = $1", [id])).rows[0].admin_id; } async updatePassword(id, password) { return (await db.query("UPDATE groups SET password = $1 WHERE id = $2", [password, id])); } async getPassword(id) { return (await db.query("SELECT password FROM groups WHERE id = $1", [id])).rows[0].password; } async getByName(name) { let res = (await db.query("SELECT id FROM groups WHERE name = $1", [name])); if (res.rowCount == 0) throw new customError(`getByName group not found`, responseCodes.responses.groups.name_not_found); return res.rows[0]; } async getUsersInGroup(groupId) { return (await db.query("SELECT id FROM users WHERE $1 = ANY(groups)", [groupId])).rows.map((group) => group.id) } async rename(groupId, newName) { await db.query("UPDATE groups SET name = $1 WHERE id = $2", [newName, groupId]).catch((e) => errorHandler(e, "groups"));; } async transferOwnership(groupId, userId) { await db.query("UPDATE groups SET admin_id = $1 WHERE id = $2", [userId, groupId]) } }; export default new GroupService();