118 lines
2.4 KiB
JavaScript
118 lines
2.4 KiB
JavaScript
import dotenv from 'dotenv';
|
|
import { userModel } from '../../schemas/management/user.schema.js';
|
|
import log4js from 'log4js';
|
|
import mongoose from 'mongoose';
|
|
import {
|
|
listObjects,
|
|
listObjectsByProperties,
|
|
getObject,
|
|
editObject,
|
|
} from '../../database/database.js';
|
|
|
|
dotenv.config();
|
|
|
|
const logger = log4js.getLogger('Users');
|
|
logger.level = process.env.LOG_LEVEL;
|
|
|
|
export const listUsersRouteHandler = async (
|
|
req,
|
|
res,
|
|
page = 1,
|
|
limit = 25,
|
|
property = '',
|
|
filter = {},
|
|
search = '',
|
|
sort = '',
|
|
order = 'ascend'
|
|
) => {
|
|
const result = await listObjects({
|
|
model: userModel,
|
|
page,
|
|
limit,
|
|
property,
|
|
filter,
|
|
search,
|
|
sort,
|
|
order,
|
|
});
|
|
|
|
if (result?.error) {
|
|
logger.error('Error listing users.');
|
|
res.status(result.code).send(result);
|
|
return;
|
|
}
|
|
|
|
logger.debug(`List of users (Page ${page}, Limit ${limit}). Count: ${result.length}`);
|
|
res.send(result);
|
|
};
|
|
|
|
export const listUsersByPropertiesRouteHandler = async (
|
|
req,
|
|
res,
|
|
properties = '',
|
|
filter = {},
|
|
masterFilter = {}
|
|
) => {
|
|
const result = await listObjectsByProperties({
|
|
model: userModel,
|
|
properties,
|
|
filter,
|
|
masterFilter,
|
|
});
|
|
|
|
if (result?.error) {
|
|
logger.error('Error listing users.');
|
|
res.status(result.code).send(result);
|
|
return;
|
|
}
|
|
|
|
logger.debug(`List of users. Count: ${result.length}`);
|
|
res.send(result);
|
|
};
|
|
|
|
export const getUserRouteHandler = async (req, res) => {
|
|
const id = req.params.id;
|
|
const result = await getObject({
|
|
model: userModel,
|
|
id,
|
|
});
|
|
if (result?.error) {
|
|
logger.warn(`User not found with supplied id.`);
|
|
return res.status(result.code).send(result);
|
|
}
|
|
logger.debug(`Retreived user with ID: ${id}`);
|
|
res.send(result);
|
|
};
|
|
|
|
export const editUserRouteHandler = async (req, res) => {
|
|
// Get ID from params
|
|
const id = new mongoose.Types.ObjectId(req.params.id);
|
|
|
|
logger.trace(`User with ID: ${id}`);
|
|
|
|
const updateData = {
|
|
updatedAt: new Date(),
|
|
name: req.body.name,
|
|
firstName: req.body.firstName,
|
|
lastName: req.body.lastName,
|
|
email: req.body.email,
|
|
};
|
|
// Create audit log before updating
|
|
const result = await editObject({
|
|
model: userModel,
|
|
id,
|
|
updateData,
|
|
user: req.user,
|
|
});
|
|
|
|
if (result.error) {
|
|
logger.error('Error editing user:', result.error);
|
|
res.status(result).send(result);
|
|
return;
|
|
}
|
|
|
|
logger.debug(`Edited user with ID: ${id}`);
|
|
|
|
res.send(result);
|
|
};
|