;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

This commit is contained in:
leca 2024-10-27 05:45:12 +03:00
parent 3388da7280
commit 09b5106538
20 changed files with 82 additions and 76 deletions

View File

@ -2,7 +2,7 @@ import AbstractProductService from '../services/abstractproduct.js';
import statuses from '../utils/status.js'; import statuses from '../utils/status.js';
import log from '../utils/log.js'; import log from '../utils/log.js';
const TAG = "/controllers/abstractproduct.js" const TAG = "/controllers/abstractproduct.js";
class AbstractProductController { class AbstractProductController {
async create(req, res) { async create(req, res) {
@ -15,8 +15,8 @@ class AbstractProductController {
case statuses.duplicate: case statuses.duplicate:
return res.status(400).send(e.message); return res.status(400).send(e.message);
default: default:
log.error(e.original) log.error(e.original);
return res.status(500).send(e.message) return res.status(500).send(e.message);
} }
} }
} }

View File

@ -1,6 +1,5 @@
import CategoryService from "../services/category.js"; import CategoryService from "../services/category.js";
import log import log from "../utils/log.js";
from "../utils/log.js";
const TAG = "controllers/category.js"; const TAG = "controllers/category.js";
class CategoryController { class CategoryController {

View File

@ -5,7 +5,7 @@ import config from '../../config.json' with {type: "json"};
import statuses from '../utils/status.js'; import statuses from '../utils/status.js';
import log from '../utils/log.js'; import log from '../utils/log.js';
const TAG = "/controllers/group.js" const TAG = "/controllers/group.js";
class GroupController { class GroupController {
async create(req, res) { async create(req, res) {

View File

@ -28,7 +28,7 @@ class AbstractProductController {
if (abstract_product_id) await ProductService.updateAbstractProductId(groupId, localId, abstract_product_id); if (abstract_product_id) await ProductService.updateAbstractProductId(groupId, localId, abstract_product_id);
if (amount) await ProductService.updateAmount(groupId, localId, amount) if (amount) await ProductService.updateAmount(groupId, localId, amount);
if (date_of_production) await ProductService.updateDateOfProduction(groupId, localId, date_of_production); if (date_of_production) await ProductService.updateDateOfProduction(groupId, localId, date_of_production);

View File

@ -15,7 +15,7 @@ class UserController {
await UserService.create(username, password); await UserService.create(username, password);
log.info(`New user with name ${username} has just registered`); log.info(`New user with name ${username} has just registered`);
return res.status(200).send("Successfull register") return res.status(200).send("Successfull register");
} catch (e) { res.status(500).send(log.unknownError(`${TAG}/register: ${e}`)); } } catch (e) { res.status(500).send(log.unknownError(`${TAG}/register: ${e}`)); }
} }
@ -35,10 +35,10 @@ class UserController {
try { try {
const { groupId } = req.params; const { groupId } = req.params;
let result = {} let result = {};
result.abstract_products = await AbstractProductService.getAll(groupId); result.abstract_products = await AbstractProductService.getAll(groupId);
result.products = await ProductService.getAll(groupId); result.products = await ProductService.getAll(groupId);
// result.categories = await CategoryService.getAll(groupId); result.categories = await CategoryService.getAll(groupId);
return res.status(200).json(result); return res.status(200).json(result);
} catch (e) { res.status(500).send(log.unknownError(`${TAG}/synchronize: ${e}`)); } } catch (e) { res.status(500).send(log.unknownError(`${TAG}/synchronize: ${e}`)); }

View File

@ -2,7 +2,7 @@ import express from 'express';
import UserRouter from './routers/user.js'; import UserRouter from './routers/user.js';
import GroupRouter from './routers/group.js'; import GroupRouter from './routers/group.js';
import AbstractProductRouter from './routers/abstractproduct.js'; import AbstractProductRouter from './routers/abstractproduct.js';
import log from './utils/log.js' import log from './utils/log.js';
import config from '../config.json' with {type: "json"}; import config from '../config.json' with {type: "json"};
import ProductRouter from './routers/product.js'; import ProductRouter from './routers/product.js';
@ -21,4 +21,4 @@ app.use('/api/category', CategoryRouter);
app.listen(config.port, () => { app.listen(config.port, () => {
log.info(`Application has started on port ${config.port}`) log.info(`Application has started on port ${config.port}`)
}) });

View File

@ -4,7 +4,7 @@ import config from '../../config.json' with {type: "json"};
import GroupService from '../services/group.js'; import GroupService from '../services/group.js';
import UserService from '../services/user.js'; import UserService from '../services/user.js';
const TAG = "/middlewares/auth.js" const TAG = "/middlewares/auth.js";
const requireUsername = async (req, res, next) => { const requireUsername = async (req, res, next) => {
if (req.method == "OPTIONS") next(); if (req.method == "OPTIONS") next();
@ -14,7 +14,7 @@ const requireUsername = async (req, res, next) => {
if (!username) return res.status(400).send("Username is required"); if (!username) return res.status(400).send("Username is required");
next(); next();
} catch (e) { return res.status(500).send(unknownError(`${TAG}/requireUsername: ${e}`)); } } catch (e) { return res.status(500).send(unknownError(`${TAG}/requireUsername: ${e}`)); }
} };
const requirePassword = async (req, res, next) => { const requirePassword = async (req, res, next) => {
if (req.method == "OPTIONS") next(); if (req.method == "OPTIONS") next();
@ -24,36 +24,36 @@ const requirePassword = async (req, res, next) => {
if (!password) return res.status(400).send("Password is required"); if (!password) return res.status(400).send("Password is required");
next(); next();
} catch (e) { return res.status(500).send(unknownError(`${TAG}/requirePassword: ${e}`)); } } catch (e) { return res.status(500).send(unknownError(`${TAG}/requirePassword: ${e}`)); }
} };
const authenticate = async (req, res, next) => { const authenticate = async (req, res, next) => {
if (req.method == "OPTIONS") next(); if (req.method == "OPTIONS") next();
try { try {
if (!req.headers.authorization) return res.status(403).send("No authorization header supplied"); if (!req.headers.authorization) return res.status(403).send("No authorization header supplied");
const token = req.headers.authorization.split(' ')[1] const token = req.headers.authorization.split(' ')[1];
if (!token) return res.status(403).send("No authorization token supplied"); if (!token) return res.status(403).send("No authorization token supplied");
if (!jwt.verify(token, config.secret)) return res.status(403).send("Authorization token is incorrect"); if (!jwt.verify(token, config.secret)) return res.status(403).send("Authorization token is incorrect");
next(); next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/authenticate: ${e}`)); } } catch (e) { return res.status(500).send(log.unknownError(`${TAG}/authenticate: ${e}`)); }
} };
const authorizeGroupOwner = async (req, res, next) => { const authorizeGroupOwner = async (req, res, next) => {
if (req.method == "OPTIONS") next(); if (req.method == "OPTIONS") next();
try { try {
const token = req.headers.authorization.split(' ')[1] const token = req.headers.authorization.split(' ')[1];
const { groupId } = req.params; const { groupId } = req.params;
let user = jwt.decode(token, config.secret) let user = jwt.decode(token, config.secret);
let adminId = await GroupService.getAdminId(groupId); let adminId = await GroupService.getAdminId(groupId);
if (user.login.id != adminId) return res.status(403).send("Not your group"); if (user.login.id != adminId) return res.status(403).send("Not your group");
next(); next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/authorizeGroupOwner: ${e}`)); } } catch (e) { return res.status(500).send(log.unknownError(`${TAG}/authorizeGroupOwner: ${e}`)); }
} };
const checkGroupPassword = async (req, res, next) => { const checkGroupPassword = async (req, res, next) => {
if (req.method == "OPTIONS") next(); if (req.method == "OPTIONS") next();
@ -68,17 +68,24 @@ const checkGroupPassword = async (req, res, next) => {
next(); next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/checkGroupPassword: ${e}`)); } } catch (e) { return res.status(500).send(log.unknownError(`${TAG}/checkGroupPassword: ${e}`)); }
} };
const userIsInGroup = async (req, res, next) => { const userIsInGroup = async (req, res, next) => {
if (req.method == "OPTIONS") next(); if (req.method == "OPTIONS") next();
const groupId = req.body.groupId || req.params.groupId; const groupId = req.body.groupId || req.params.groupId;
const token = req.headers.authorization.split(' ')[1] const token = req.headers.authorization.split(' ')[1];
let user = jwt.decode(token, config.secret) let user = jwt.decode(token, config.secret);
if (!await UserService.isInGroup(user.login.id, groupId)) return res.status(403).send("You are not a member of this group"); if (!await UserService.isInGroup(user.login.id, groupId)) return res.status(403).send("You are not a member of this group");
next(); next();
} };
export default { requireUsername, requirePassword, authenticate, authorizeGroupOwner, checkGroupPassword, userIsInGroup } export default {
requireUsername,
requirePassword,
authenticate,
authorizeGroupOwner,
checkGroupPassword,
userIsInGroup
};

View File

@ -6,7 +6,7 @@ import CategoryService from '../services/category.js';
import log from '../utils/log.js'; import log from '../utils/log.js';
import statuses from '../utils/status.js'; import statuses from '../utils/status.js';
const TAG = "/middlewares/existance.js" const TAG = "/middlewares/existance.js";
const usernameExists = async (req, res, next) => { const usernameExists = async (req, res, next) => {
try { try {
@ -26,7 +26,7 @@ const usernameDoesntExist = async (req, res, next) => {
if (user != undefined && user != statuses.not_found) return res.status(400).send("Such username already taken"); if (user != undefined && user != statuses.not_found) return res.status(400).send("Such username already taken");
next(); next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/usernameDoesntExist: ${e}`)); } } catch (e) { return res.status(500).send(log.unknownError(`${TAG}/usernameDoesntExist: ${e}`)); }
} };
const groupExists = async (req, res, next) => { const groupExists = async (req, res, next) => {
try { try {
@ -37,7 +37,7 @@ const groupExists = async (req, res, next) => {
if (!group || group == statuses.not_found) return res.status(404).send("Group not found"); if (!group || group == statuses.not_found) return res.status(404).send("Group not found");
next(); next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/groupExists: ${e}`)) } } catch (e) { return res.status(500).send(log.unknownError(`${TAG}/groupExists: ${e}`)) }
} };
const groupDoesntExist = async (req, res, next) => { const groupDoesntExist = async (req, res, next) => {
try { try {
@ -48,7 +48,7 @@ const groupDoesntExist = async (req, res, next) => {
if (group || group != statuses.not_found) return res.status(400).send("Such group already exists"); if (group || group != statuses.not_found) return res.status(400).send("Such group already exists");
next(); next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/groupDoesntExist: ${e}`)) } } catch (e) { return res.status(500).send(log.unknownError(`${TAG}/groupDoesntExist: ${e}`)) }
} };
const groupNameDoesntExist = async (req, res, next) => { const groupNameDoesntExist = async (req, res, next) => {
try { try {
@ -57,8 +57,8 @@ const groupNameDoesntExist = async (req, res, next) => {
let group = await GroupService.getByName(groupName); let group = await GroupService.getByName(groupName);
if (group) return res.status(400).send("Such group name already exists"); if (group) return res.status(400).send("Such group name already exists");
next(); next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/groupNameDoesntExist: ${e}`)) } } catch (e) { return res.status(500).send(log.unknownError(`${TAG}/groupNameDoesntExist: ${e}`)); }
} };
const abstractProductExists = async (req, res, next) => { const abstractProductExists = async (req, res, next) => {
try { try {
@ -67,8 +67,8 @@ const abstractProductExists = async (req, res, next) => {
let result = await AbstractProductService.exists(groupId, localId); let result = await AbstractProductService.exists(groupId, localId);
if (!result) return res.status(404).send("Abstract product not found"); if (!result) return res.status(404).send("Abstract product not found");
next(); next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/abstractProductExists: ${e}`)) } } catch (e) { return res.status(500).send(log.unknownError(`${TAG}/abstractProductExists: ${e}`)); }
} };
const productExists = async (req, res, next) => { const productExists = async (req, res, next) => {
try { try {
@ -77,8 +77,8 @@ const productExists = async (req, res, next) => {
let result = await ProductService.exists(groupId, localId); let result = await ProductService.exists(groupId, localId);
if (!result) return res.status(404).send("Product not found"); if (!result) return res.status(404).send("Product not found");
next(); next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/productExists: ${e}`)) } } catch (e) { return res.status(500).send(log.unknownError(`${TAG}/productExists: ${e}`)); }
} };
const categoryNameDoesntExist = async (req, res, next) => { const categoryNameDoesntExist = async (req, res, next) => {
try { try {
@ -87,8 +87,8 @@ const categoryNameDoesntExist = async (req, res, next) => {
let result = await CategoryService.getByName(groupId, localId, categoryName); let result = await CategoryService.getByName(groupId, localId, categoryName);
if (result != statuses.not_found) return res.status(400).send("Such category name exists"); if (result != statuses.not_found) return res.status(400).send("Such category name exists");
next(); next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/categoryNameDoesntExist: ${e}`)) } } catch (e) { return res.status(500).send(log.unknownError(`${TAG}/categoryNameDoesntExist: ${e}`)); }
} };
const categoryExists = async (req, res, next) => { const categoryExists = async (req, res, next) => {
try { try {
@ -97,8 +97,8 @@ const categoryExists = async (req, res, next) => {
let result = await CategoryService.getById(groupId, localId); let result = await CategoryService.getById(groupId, localId);
if (!result || result == statuses.not_found) return res.status(404).send("No such category"); if (!result || result == statuses.not_found) return res.status(404).send("No such category");
next(); next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/categoryExists: ${e}`)) } } catch (e) { return res.status(500).send(log.unknownError(`${TAG}/categoryExists: ${e}`)); }
} };
export default { export default {
usernameExists, usernameExists,
@ -113,4 +113,4 @@ export default {
categoryNameDoesntExist, categoryNameDoesntExist,
categoryExists categoryExists
} };

View File

@ -1,11 +1,11 @@
import { Router } from 'express'; import { Router } from 'express';
import auth from '../middlewares/auth.js'; import auth from '../middlewares/auth.js';
import AbstractProductController from '../controllers/abstractproduct.js' import AbstractProductController from '../controllers/abstractproduct.js';
import existance from '../middlewares/existance.js'; import existance from '../middlewares/existance.js';
const AbstractProductRouter = new Router(); const AbstractProductRouter = new Router();
AbstractProductRouter.post('/create', auth.authenticate, existance.groupExists, auth.userIsInGroup, AbstractProductController.create); AbstractProductRouter.post('/create', auth.authenticate, existance.groupExists, auth.userIsInGroup, AbstractProductController.create);
AbstractProductRouter.post('/update', auth.authenticate, existance.groupExists, auth.userIsInGroup, existance.abstractProductExists, AbstractProductController.update) AbstractProductRouter.post('/update', auth.authenticate, existance.groupExists, auth.userIsInGroup, existance.abstractProductExists, AbstractProductController.update);
export default AbstractProductRouter; export default AbstractProductRouter;

View File

@ -6,6 +6,6 @@ import CategoryController from '../controllers/category.js';
const CategoryRouter = new Router(); const CategoryRouter = new Router();
CategoryRouter.post('/create', auth.authenticate, existance.groupExists, existance.categoryNameDoesntExist, CategoryController.create); CategoryRouter.post('/create', auth.authenticate, existance.groupExists, existance.categoryNameDoesntExist, CategoryController.create);
CategoryRouter.post('/update', auth.authenticate, existance.groupExists, existance.categoryExists, CategoryController.update) CategoryRouter.post('/update', auth.authenticate, existance.groupExists, existance.categoryExists, CategoryController.update);
export default CategoryRouter; export default CategoryRouter;

View File

@ -1,12 +1,12 @@
import { Router } from 'express'; import { Router } from 'express';
import auth from '../middlewares/auth.js'; import auth from '../middlewares/auth.js';
import GroupController from '../controllers/group.js' import GroupController from '../controllers/group.js';
import existance from '../middlewares/existance.js'; import existance from '../middlewares/existance.js';
const GroupRouter = new Router(); const GroupRouter = new Router();
GroupRouter.post('/create/:groupName', auth.authenticate, existance.groupNameDoesntExist, GroupController.create); GroupRouter.post('/create/:groupName', auth.authenticate, existance.groupNameDoesntExist, GroupController.create);
GroupRouter.post('/join/:groupId', auth.authenticate, existance.groupExists, auth.requirePassword, auth.checkGroupPassword, GroupController.join); GroupRouter.post('/join/:groupId', auth.authenticate, existance.groupExists, auth.requirePassword, auth.checkGroupPassword, GroupController.join);
GroupRouter.post('/password/:groupId', auth.authenticate, existance.groupExists, auth.authorizeGroupOwner, auth.requirePassword, GroupController.updatePassword) GroupRouter.post('/password/:groupId', auth.authenticate, existance.groupExists, auth.authorizeGroupOwner, auth.requirePassword, GroupController.updatePassword);
export default GroupRouter; export default GroupRouter;

View File

@ -6,6 +6,6 @@ import existance from '../middlewares/existance.js';
const ProductRouter = new Router(); const ProductRouter = new Router();
ProductRouter.post('/create', auth.authenticate, existance.groupExists, auth.userIsInGroup, ProductController.create); ProductRouter.post('/create', auth.authenticate, existance.groupExists, auth.userIsInGroup, ProductController.create);
ProductRouter.post('/update', auth.authenticate, existance.groupExists, auth.userIsInGroup, existance.productExists, ProductController.update) ProductRouter.post('/update', auth.authenticate, existance.groupExists, auth.userIsInGroup, existance.productExists, ProductController.update);
export default ProductRouter; export default ProductRouter;

View File

@ -1,7 +1,7 @@
import { Router } from 'express'; import { Router } from 'express';
import auth from '../middlewares/auth.js'; import auth from '../middlewares/auth.js';
import existance from '../middlewares/existance.js'; import existance from '../middlewares/existance.js';
import UserController from '../controllers/user.js' import UserController from '../controllers/user.js';
const UserRouter = new Router(); const UserRouter = new Router();

View File

@ -53,9 +53,9 @@ class AbstractProductService {
} }
async getAll(groupId) { async getAll(groupId) {
let result = (await db.query("SELECT local_id, barcode, name, net_weight, image_filename, category, unit FROM abstract_products WHERE group_id = $1", [groupId])).rows let result = (await db.query("SELECT local_id, barcode, name, net_weight, image_filename, category, unit FROM abstract_products WHERE group_id = $1", [groupId])).rows;
if (!result) return statuses.not_found; if (!result) return statuses.not_found;
return result return result;
} }
async exists(groupId, localId) { async exists(groupId, localId) {

View File

@ -3,7 +3,7 @@ import statuses from '../utils/status.js';
class CategoryService { class CategoryService {
async create(groupId, categoryId, name) { async create(groupId, categoryId, name) {
await db.query("INSERT INTO categories (group_id, local_id, name) VALUES ($1, $2, $3)", [groupId, categoryId, name]) await db.query("INSERT INTO categories (group_id, local_id, name) VALUES ($1, $2, $3)", [groupId, categoryId, name]);
} }
async update(groupId, categoryId, name) { async update(groupId, categoryId, name) {
@ -13,7 +13,7 @@ class CategoryService {
async getById(groupId, localId) { async getById(groupId, localId) {
let result = (await db.query("SELECT * FROM categories WHERE group_id = $1 AND local_id = $2", [groupId, localId])) let result = (await db.query("SELECT * FROM categories WHERE group_id = $1 AND local_id = $2", [groupId, localId]))
if (result.rowCount == 0) return statuses.not_found; if (result.rowCount == 0) return statuses.not_found;
return result.rows[0] return result.rows[0];
} }
async getByName(groupId, localId, name) { async getByName(groupId, localId, name) {

View File

@ -4,19 +4,19 @@ import status from '../utils/status.js';
class GroupService { class GroupService {
async create(name, creatorId) { async create(name, creatorId) {
let res = await db.query("INSERT INTO groups (name, admin_id) VALUES ($1, $2) RETURNING ID", [name, creatorId]).catch(errorHandler) let res = await db.query("INSERT INTO groups (name, admin_id) VALUES ($1, $2) RETURNING ID", [name, creatorId]).catch(errorHandler);
return res.rows[0]; return res.rows[0];
} }
async getById(id) { async getById(id) {
let res = (await db.query("SELECT * FROM groups WHERE id = $1", [id])) let res = (await db.query("SELECT * FROM groups WHERE id = $1", [id]));
if (res.rowCount == 0) return status.not_found; if (res.rowCount == 0) return status.not_found;
return res.rows[0]; return res.rows[0];
} }
async getAdminId(id) { async getAdminId(id) {
return (await db.query("SELECT admin_id FROM groups WHERE ID = $1", [id])).rows[0].admin_id return (await db.query("SELECT admin_id FROM groups WHERE ID = $1", [id])).rows[0].admin_id;
} }
async updatePassword(id, password) { async updatePassword(id, password) {
@ -28,7 +28,7 @@ class GroupService {
} }
async getByName(name) { async getByName(name) {
return (await db.query("SELECT * FROM groups WHERE name = $1", [name])).rows[0] return (await db.query("SELECT * FROM groups WHERE name = $1", [name])).rows[0];
} }
}; };

View File

@ -7,7 +7,7 @@ class ProductService {
await db.query("INSERT INTO products (group_id, local_id, abstract_product_id, amount, date_of_production, expiry_date) VALUES ($1, $2, $3, $4, $5, $6)", [groupid, localid, abstract_product_id, amount, date_of_production, expiry_date]) await db.query("INSERT INTO products (group_id, local_id, abstract_product_id, amount, date_of_production, expiry_date) VALUES ($1, $2, $3, $4, $5, $6)", [groupid, localid, abstract_product_id, amount, date_of_production, expiry_date])
.catch((e) => { .catch((e) => {
errorHandler(e, "Abstract Product") errorHandler(e, "Abstract Product")
}) });
} }
async updateAbstractProductId(groupId, localId, abstract_product_id) { async updateAbstractProductId(groupId, localId, abstract_product_id) {
@ -29,20 +29,20 @@ class ProductService {
await db.query("UPDATE products SET date_of_production = $1 WHERE group_id = $2 AND local_id = $3", [date_of_production, groupId, localId]) await db.query("UPDATE products SET date_of_production = $1 WHERE group_id = $2 AND local_id = $3", [date_of_production, groupId, localId])
.catch((e) => { .catch((e) => {
errorHandler(e, "date of production") errorHandler(e, "date of production")
}) });
} }
async updateExpiryDate(groupId, localId, expiry_date) { async updateExpiryDate(groupId, localId, expiry_date) {
await db.query("UPDATE products SET expiry_date = $1 WHERE group_id = $2 AND local_id = $3", [expiry_date, groupId, localId]) await db.query("UPDATE products SET expiry_date = $1 WHERE group_id = $2 AND local_id = $3", [expiry_date, groupId, localId])
.catch((e) => { .catch((e) => {
errorHandler(e, "expiry date") errorHandler(e, "expiry date")
}) });
} }
async getAll(groupId) { async getAll(groupId) {
let result = (await db.query("SELECT local_id, abstract_product_id, amount, date_of_production, expiry_date FROM products WHERE group_id = $1", [groupId])).rows let result = (await db.query("SELECT local_id, abstract_product_id, amount, date_of_production, expiry_date FROM products WHERE group_id = $1", [groupId])).rows;
if (!result) return statuses.not_found; if (!result) return statuses.not_found;
return result return result;
} }
async exists(groupId, localId) { async exists(groupId, localId) {

View File

@ -5,14 +5,14 @@ import bcrypt from 'bcrypt';
class UserService { class UserService {
async create(username, password) { async create(username, password) {
await db.query("INSERT INTO users (username, password) VALUES ($1, $2)", [username, bcrypt.hashSync(password, 12)]).catch((e) => { await db.query("INSERT INTO users (username, password) VALUES ($1, $2)", [username, bcrypt.hashSync(password, 12)]).catch((e) => {
errorHandler(e, "user") errorHandler(e, "user");
}) })
return statuses.ok return statuses.ok;
} }
async getByUsername(username) { async getByUsername(username) {
let user = (await db.query("SELECT * FROM Users WHERE username = $1", [username])).rows let user = (await db.query("SELECT * FROM Users WHERE username = $1", [username])).rows;
if (user == undefined) return statuses.not_found if (user == undefined) return statuses.not_found;
return (user[0]); return (user[0]);
} }

View File

@ -1,24 +1,24 @@
import config from '../../config.json' with {type: "json"}; import config from '../../config.json' with {type: "json"};
const debug = (text) => { const debug = (text) => {
if (config.debug) console.debug(`[D] [${Date()}]: ${text}`) if (config.debug) console.debug(`[D] [${Date()}]: ${text}`);
} }
const info = (text) => { const info = (text) => {
console.log(`[I] [${Date()}]: ${text}`) console.log(`[I] [${Date()}]: ${text}`);
} }
const error = (text) => { const error = (text) => {
console.error(`[E] [${Date()}]: ${text}`) console.error(`[E] [${Date()}]: ${text}`);
} }
const warn = (text) => { const warn = (text) => {
console.warn(`[W] [${Date()}]: ${text}`) console.warn(`[W] [${Date()}]: ${text}`);
} }
const unknownError = (text) => { const unknownError = (text) => {
error(text); error(text);
return "Unknown server error. Please, report to the developer" return "Unknown server error. Please, report to the developer";
} }
export default { debug, info, error, warn, unknownError } export default { debug, info, error, warn, unknownError };

View File

@ -1,4 +1,4 @@
import statuses from "./status.js" import statuses from "./status.js";
const errorHandler = (e, obj) => { const errorHandler = (e, obj) => {
switch (e.code) { switch (e.code) {
@ -6,24 +6,24 @@ const errorHandler = (e, obj) => {
throw { throw {
status: statuses.duplicate, status: statuses.duplicate,
message: `Such ${obj} already exists` message: `Such ${obj} already exists`
} };
case '22007': case '22007':
throw { throw {
status: statuses.invalid_syntax, status: statuses.invalid_syntax,
message: `Invalid syntax in ${obj}` message: `Invalid syntax in ${obj}`
} };
case '22001': case '22001':
throw { throw {
status: statuses.invalid_syntax, status: statuses.invalid_syntax,
message: `Value too long (${obj})` message: `Value too long (${obj})`
} };
default: default:
throw { throw {
status: statuses.unknown, status: statuses.unknown,
message: `Unknown error. Please, report to the developer`, message: `Unknown error. Please, report to the developer`,
original: e original: e
} };
} };
}; };
export default errorHandler; export default errorHandler;