56 lines
2.3 KiB
JavaScript
56 lines
2.3 KiB
JavaScript
import db from '../db.js'
|
|
import customError from '../response/customError.js';
|
|
import responseCodes from '../response/responseCodes.js';
|
|
import bcrypt from 'bcrypt';
|
|
import errorHandler from '../utils/pgerrorhandler.js';
|
|
|
|
class UserService {
|
|
async create(username, password) {
|
|
let result = (await db.query("INSERT INTO users (username, password) VALUES ($1, $2) RETURNING id", [username, bcrypt.hashSync(password, 12)]).catch((e) => {
|
|
errorHandler(e, "user");
|
|
})).rows[0].id
|
|
|
|
return result
|
|
}
|
|
|
|
async getByUsername(username) {
|
|
let user = (await db.query("SELECT * FROM Users WHERE username = $1", [username]));
|
|
if (user.rowCount == 0) throw new customError(`getByUsername user not found`, responseCodes.responses.usernames.not_found);
|
|
return user.rows[0];
|
|
}
|
|
|
|
async getAll() {
|
|
let res = await db.query("SELECT * FROM Users");
|
|
if (res.rowCount == 0) throw new customError(`getAll user not found`, responseCodes.responses.usernames.not_found);
|
|
return res.rows[0]
|
|
}
|
|
|
|
async isInGroup(userId, groupId) {
|
|
return (await db.query("SELECT * FROM Users WHERE ID = $1 AND $2 = ANY(groups)", [userId, groupId])).rowCount > 0;
|
|
}
|
|
|
|
async joinGroup(userId, groupId) {
|
|
if (await (this.isInGroup(userId, groupId))) throw new customError(`joinGroup user already in group`, responseCodes.responses.user.already_in_group);
|
|
await db.query("UPDATE Users SET groups = array_append(groups, $1::integer) WHERE ID = $2", [groupId, userId]);
|
|
}
|
|
|
|
async changeUsername(userId, username) {
|
|
await db.query("UPDATE users SET username = $1 WHERE id = $2", [username, userId]).catch(e => errorHandler(e, "user"));
|
|
}
|
|
|
|
async changePassword(userId, password) {
|
|
await db.query("UPDATE users SET password = $1 WHERE id = $2", [bcrypt.hashSync(password, 12), userId])
|
|
}
|
|
|
|
async getAllGroupsForUser(userId) {
|
|
return (await db.query("SELECT groups FROM users WHERE id = $1", [userId])).rows[0].groups
|
|
}
|
|
|
|
async getById(userId) {
|
|
let res = (await db.query("SELECT * FROM users WHERE id = $1", [userId]))
|
|
if (res.rowCount == 0) throw new customError(`getById no user found`, responseCodes.responses.user.not_found)
|
|
return res.rows[0]
|
|
}
|
|
}
|
|
|
|
export default new UserService(); |