Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Task 5 #5

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions config/logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import winston from "winston";

const { combine, timestamp, printf } = winston.format;

const myFormat = printf(({ level, message, timestamp }) => {
return `${timestamp} ${level}: ${JSON.stringify(message)}`;
});

export const logger = winston.createLogger({
level: 'info',
format: combine(
timestamp(),
myFormat,
),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
],
});
76 changes: 61 additions & 15 deletions controllers/group.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,72 @@
import { logger } from "../config/logger";
import { groupService } from "../services/group";

export const getGroup = async (req, res) => {
const groupData = await groupService.getById(req.params.id);
res.status(200).json(groupData);
export const getGroup = async (req, res, next) => {
const METHOD = 'getGroup';

try {
const groupData = await groupService.getById(req.params.id);
logger.log('info', JSON.stringify({ method: METHOD, id: req.params.id }));
res.status(200).json(groupData);
}
catch (error) {
const err = new DatabaseError(error.message);
next({ error: err, method: METHOD, params: { id: req.params.id } });
}
};

export const getGroups = async (req, res) => {
const groupData = await groupService.getList();
res.status(200).json(groupData);
export const getGroups = async (req, res, next) => {
const METHOD = 'getGroups';

try {
const groupData = await groupService.getList();
logger.log('info', JSON.stringify({ method: METHOD }));
res.status(200).json(groupData);
}
catch (error) {
const err = new DatabaseError(error.message);
next({ error: err, method: METHOD });
}
};

export const createGroup = async (req, res) => {
const groupData = await groupService.create(req.body);
res.status(200).json(groupData);
export const createGroup = async (req, res, next) => {
const METHOD = 'createGroup';

try {
const groupData = await groupService.create(req.body);
logger.log('info', JSON.stringify({ method: METHOD, params: req.body }));
res.status(200).json(groupData);
}
catch (error) {
const err = new DatabaseError(error.message);
next({ error: err, method: METHOD, params: req.body });
}
};

export const editGroup = async (req, res) => {
const groupData = await groupService.edit(req.body);
res.status(200).json(groupData);
export const editGroup = async (req, res, next) => {
const METHOD = 'editGroup';

try {
const groupData = await groupService.edit(req.body);
logger.log('info', JSON.stringify({ method: METHOD, params: req.body }));
res.status(200).json(groupData);
}
catch (error) {
const err = new DatabaseError(error.message);
next({ error: err, method: METHOD, params: req.body });
}
};

export const deleteGroup = async (req, res) => {
await groupService.delete(req.params.id);
res.status(200).send();
export const deleteGroup = async (req, res, next) => {
const METHOD = 'deleteGroup';

try {
await groupService.delete(req.params.id);
logger.log('info', JSON.stringify({ method: METHOD, id: req.params.id }));
res.status(200).send();
}
catch (error) {
const err = new DatabaseError(error.message);
next({ error: err, method: METHOD, params: { id: req.params.id } });
}
};
77 changes: 62 additions & 15 deletions controllers/user.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,73 @@
import { logger } from "../config/logger";
import DatabaseError from "../helpers/errors/databaseError";
import { userService } from "../services/user";

export const getUser = async (req, res) => {
const userData = await userService.getById(req.params.id);
res.status(200).json(userData);
export const getUser = async (req, res, next) => {
const METHOD = 'getUser';

try {
const userData = await userService.getById(req.params.id);
logger.log('info', JSON.stringify({ method: METHOD, id: req.params.id }));
res.status(200).json(userData);
}
catch (error) {
const err = new DatabaseError(error.message);
next({ error: err, method: METHOD, params: { id: req.params.id }});
}
};

export const getUsers = async (req, res) => {
const usersData = await userService.getList(req.query.loginSubstring, req.query.limit);
res.status(200).json(usersData);
export const getUsers = async (req, res, next) => {
const METHOD = 'getUsers';

try {
const usersData = await userService.getList(req.query.loginSubstring, req.query.limit);
logger.log('info', JSON.stringify({ method: METHOD, substring: req.query.loginSubstring, limit: req.query.limit }));
res.status(200).json(usersData);
}
catch (error) {
const err = new DatabaseError(error.message);
next({ error: err, method: METHOD, params: { substring: req.query.loginSubstring, limit: req.query.limit } });
}
};

export const createUser = async (req, res) => {
const userData = await userService.create(req.body);
res.status(200).json(userData);
export const createUser = async (req, res, next) => {
const METHOD = 'createUser';

try {
const userData = await userService.create(req.body);
logger.log('info', JSON.stringify({ method: METHOD, params: req.body }));
res.status(200).json(userData);
}
catch (error) {
const err = new DatabaseError(error.message);
next({ error: err, method: METHOD, params: req.body });
}
};

export const editUser = async (req, res) => {
const userData = await userService.edit(req.body);
res.status(200).json(userData);
export const editUser = async (req, res, next) => {
const METHOD = 'editUser';

try {
const userData = await userService.edit(req.body);
logger.log('info', JSON.stringify({ method: METHOD, params: req.body }));
res.status(200).json(userData);
}
catch (error) {
const err = new DatabaseError(error.message);
next({ error: err, method: METHOD, params: req.body });
}
};

export const deleteUser = async (req, res) => {
await userService.delete(req.params.id);
res.status(200).send();
export const deleteUser = async (req, res, next) => {
const METHOD = 'deleteUser';

try {
await userService.delete(req.params.id);
logger.log('info', JSON.stringify({ method: METHOD, id: req.params.id }));
res.status(200).send();
}
catch (error) {
const err = new DatabaseError(error.message);
next({ error: err, method: METHOD, params: { id: req.params.id } });
}
};
32 changes: 26 additions & 6 deletions controllers/userGroup.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,31 @@
import { logger } from "../config/logger";
import DatabaseError from "../helpers/errors/databaseError";
import { userGroupService } from "../services/userGroup"

export const getUserGroups = async (req, res) => {
const userGroupsData = await userGroupService.getList();
res.status(200).json(userGroupsData);
export const getUserGroups = async (req, res, next) => {
const METHOD = 'getUserGroups';

try {
const userGroupsData = await userGroupService.getList();
logger.log('info', JSON.stringify({ method: METHOD }));
res.status(200).json(userGroupsData);
}
catch (error) {
const err = new DatabaseError(error.message);
next({ error: err, method: METHOD });
}
};

export const addUserGroup = async (req, res) => {
const userGroupData = await userGroupService.create(req.body);
res.status(200).json(userGroupData);
export const addUserGroup = async (req, res, next) => {
const METHOD = 'addUserGroup';

try {
const userGroupData = await userGroupService.create(req.body);
logger.log('info', JSON.stringify({ method: METHOD, params: req.body }));
res.status(200).json(userGroupData);
}
catch (error) {
const err = new DatabaseError(error.message);
next({ error: err, method: METHOD, params: req.body });
}
};
7 changes: 7 additions & 0 deletions helpers/errors/databaseError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import ExtendError from './errorExtention';

export default class DatabaseError extends ExtendError {
constructor(message) {
super(500, message || 'Database Error')
}
}
17 changes: 17 additions & 0 deletions helpers/errors/errorExtention.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export default class ExtendError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}

getResponse() {
return {
status: 'Failed',
message: this.message
};
}

getStatus() {
return this.status;
}
}
16 changes: 16 additions & 0 deletions helpers/errors/errorHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { logger } from "../../config/logger";
import DatabaseError from "./databaseError";
import NotFoundError from "./notFoundError";

const customErrors = [DatabaseError, NotFoundError];

export const customErrorHandler = ({ error, method, params }, res) => {
if (customErrors.includes(error.constructor)) {
logger.log('error', JSON.stringify({ status: error.status, message: error.message, method: method, params: params }));

return res.status(error.status).json({ status: error.status, message: error.message });
}

logger.log('error', JSON.stringify({ unhandledError: error.message, method: method, params: params }));
throw new Error(error);
};
7 changes: 7 additions & 0 deletions helpers/errors/notFoundError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import ExtendError from './errorExtention';

export default class NotFoundError extends ExtendError {
constructor(message) {
super(404, message || 'Not Found')
}
}
24 changes: 24 additions & 0 deletions helpers/initLogger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { logger } from "../config/logger";

export const initLogger = app => {
app.use((req, res, next) => {
const dataMessage = [];

dataMessage.push(JSON.stringify({ url: req.originalUrl }));

if (!isObjEmpty(req.params)) {
dataMessage.push(JSON.stringify({ params: req.params }));
}

if (!isObjEmpty(req.body)) {
dataMessage.push(JSON.stringify({ body: req.body }));
}

logger.log('info', dataMessage.toString());
next();
});

const isObjEmpty = obj => {
return Object.keys(obj).length === 0 && obj.constructor === Object;
}
}
5 changes: 0 additions & 5 deletions helpers/users.csv

This file was deleted.

17 changes: 0 additions & 17 deletions helpers/users_from_csv.js

This file was deleted.

15 changes: 7 additions & 8 deletions loaders/index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { routerLoader } from "./routerLoader";
import { sequelize } from "../config/db";
import { logger } from "../config/logger";

export const loaders = (app) => {
sequelize
.authenticate()
.then(() => {
console.log('Connection to database!');
})
.catch(err => {
console.log('Can\'t connect to database!');
process.on('uncaughtException', err => {
logger.log('error', 'UncaughtException happens... System shut down' + JSON.stringify(err));
process.exit(1);
});
process.on('unhandledRejection', err => {
logger.log('error', 'UnhandledRejection happens... Please, stay on your place.' + JSON.stringify(err));
});

routerLoader(app);
Expand Down
16 changes: 16 additions & 0 deletions loaders/routerLoader.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
import { json } from "express";
import { API_PREFIX } from "../config";
import { customErrorHandler } from "../helpers/errors/errorHandler";
import NotFoundError from "../helpers/errors/notFoundError";
import { initLogger } from "../helpers/initLogger";
import { apiRouter } from "../routers/index";

export const routerLoader = (app) => {
app.use(json());

initLogger(app);

app.use(API_PREFIX, apiRouter());

app.use((req, res, next) => {
const error = new NotFoundError();
next({ error });
});

app.use((error, req, res, next) => {
customErrorHandler(error, res);
next();
});
};
4 changes: 3 additions & 1 deletion models/user.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { User } from "../db-layer/userDB";
import { Op } from "sequelize";
import DatabaseError from "../helpers/errors/databaseError";
import NotFoundError from "../helpers/errors/notFoundError";

export const userModel = {
getById: (userId) => {
return User.findByPk(userId).catch((err) => console.error(err));
return User.findByPk(userId);
},

getList: (loginSubstr, limit) => {
Expand Down
Loading