diff --git a/.eslintrc.json b/.eslintrc.json index 9c1cde0..0e0d61e 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -7,10 +7,10 @@ }, "extends": [ "standard", - "eslint:recommended", + "eslint:all", "plugin:promise/recommended", "plugin:eqeqeq-fix/recommended", - "plugin:react/recommended", + "plugin:react/all", "plugin:react-hooks/recommended" ], "parserOptions": { @@ -25,13 +25,45 @@ "indent": [2], "quotes": [2, "single"], "linebreak-style": [2, "unix"], - "react-hooks/rules-of-hooks": "error", - "react-hooks/exhaustive-deps": "error" - // "no-console":"error" + "no-console":"off", + "no-ternary":"off", + "radix": "off", + "max-statements":"off", + "max-lines-per-function":"off", + "sort-keys-fix/sort-keys-fix": "warn", + "id-length":"off", + "no-magic-numbers":"off", + "require-unicode-regexp":"off", + "max-params":"off", + "prefer-destructuring":"off", + "no-multi-assign":"off", + "simple-import-sort/imports": "error", + "simple-import-sort/exports": "error", + "consistent-return":"off", + "max-lines":"off", + "no-plusplus":"off", + "no-continue":"off", + "no-await-in-loop":"off", + "sort-imports": ["error", { + "ignoreCase": true, + "ignoreDeclarationSort": true, + "ignoreMemberSort": true, + "memberSyntaxSortOrder": ["multiple", "all","single","none"] + }] }, "settings": { "react": { "version": "detect" } - } + }, + "plugins":[ + "react", + "promise", + "react", + "react-hooks", + "eqeqeq-fix", + "sort-keys-fix", + "unused-imports", + "simple-import-sort" + ] } \ No newline at end of file diff --git a/Controllers/constantController.js b/Controllers/constantController.js index d0cd446..7330cc3 100644 --- a/Controllers/constantController.js +++ b/Controllers/constantController.js @@ -1,33 +1,31 @@ -import getError from '#utils/error.js'; -import { permissionList } from '#constants/permission.js'; import { actionEvents } from '#constants/actionEvents.js'; +import { permissionList } from '#constants/permission.js'; +import getError from '#utils/error.js'; -const getAllPermission = async (req, res) => { - /* #swagger.tags = ["Constant"] - #swagger.security = [{"apiKeyAuth": []}] - */ +const getAllPermission = (req, res) => { + /* + * #swagger.tags = ["Constant"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const data = permissionList.sort((a, b) => { - return a.name > b.name ? 1 : -1; - }); + const data = permissionList.sort((a, b) => a.name > b.name ? 1 : -1); return res.status(200).json(data); } catch (error) { getError(error, res); } }; -const getAllActionEvent = async (req, res) => { - /* #swagger.tags = ["Constant"] - #swagger.security = [{"apiKeyAuth": []}] - */ +const getAllActionEvent = (req, res) => { + /* + * #swagger.tags = ["Constant"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const data = actionEvents.sort((a, b) => { - return a.name > b.name ? 1 : -1; - }); + const data = actionEvents.sort((a, b) => a.name > b.name ? 1 : -1); return res.status(200).json(data); } catch (error) { getError(error, res); } }; -export { getAllPermission, getAllActionEvent }; +export { getAllActionEvent, getAllPermission }; diff --git a/Controllers/dashboardController.js b/Controllers/dashboardController.js index 33f51bc..cedc416 100644 --- a/Controllers/dashboardController.js +++ b/Controllers/dashboardController.js @@ -1,6 +1,7 @@ +import { Op, Sequelize } from 'sequelize'; + import db from '#utils/dataBaseConnection.js'; import getError from '#utils/error.js'; -import { Sequelize, Op } from 'sequelize'; const User = db.users; const TestCase = db.testCases; const ReusableProcess = db.reusableProcess; @@ -9,20 +10,17 @@ const UserProject = db.userProjects; const Project = db.projects; const ExecutionHistory = db.executionHistory; export const dashboard = async (req, res) => { - /* #swagger.tags = ["Dashboard"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Dashboard"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const user = await User.schema(req.database).findAll(); // Users Start - const Active = user.filter((el) => { - return el.active === true; - }).length; + const Active = user.filter((el) => el.active === true).length; - const Unverified = user.filter((el) => { - return el.verifiedAt === null; - }).length; + const Unverified = user.filter((el) => el.verifiedAt === null).length; const Inactive = user.length - Active - Unverified; // Users End @@ -35,9 +33,9 @@ export const dashboard = async (req, res) => { where: { executedByUser: req.user.id } }); return res.status(200).json({ + executionHistoryCount, project: userProject, - user: { total: user.length, Active, Inactive, Unverified }, - executionHistoryCount + user: { Active, Inactive, Unverified, total: user.length } }); } catch (error) { getError(error, res); @@ -45,9 +43,10 @@ export const dashboard = async (req, res) => { }; export const createdReport = async (req, res) => { - /* #swagger.tags = ["Dashboard"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Dashboard"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const reusableProcess = await ReusableProcess.schema(req.database).count({ where: { createdByUser: req.body.userId } @@ -64,10 +63,10 @@ export const createdReport = async (req, res) => { }); return res.status(200).json({ + Object: object, Projects: projects, - TestCase: testCase, Reusable: reusableProcess, - Object: object + TestCase: testCase }); } catch (error) { getError(error, res); @@ -75,27 +74,24 @@ export const createdReport = async (req, res) => { }; export const executionReport = async (req, res) => { - /* #swagger.tags = ["Dashboard"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Dashboard"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const totalHistory = await ExecutionHistory.schema(req.database).findAll({ where: req.body }); - const incompleteHistory = totalHistory.filter((el) => { - return el.dataValues.finishedAt === null; - }); + const incompleteHistory = totalHistory.filter((el) => el.dataValues.finishedAt === null); - const passedHistory = totalHistory.filter((el) => { - return el.dataValues.result === true; - }); + const passedHistory = totalHistory.filter((el) => el.dataValues.result === true); const failedHistory = totalHistory.length - passedHistory.length - incompleteHistory.length; return res.status(200).json({ - Total: totalHistory.length, + Failed: failedHistory, Incomplete: incompleteHistory.length, Passed: passedHistory.length, - Failed: failedHistory + Total: totalHistory.length }); } catch (error) { getError(error, res); @@ -103,9 +99,10 @@ export const executionReport = async (req, res) => { }; export const detailedExecutionReport = async (req, res) => { - /* #swagger.tags = ["Dashboard"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Dashboard"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const startDate = new Date(req.body.startDate); const endDate = new Date(req.body.endDate); @@ -121,19 +118,19 @@ export const detailedExecutionReport = async (req, res) => { } const passedHistory = await ExecutionHistory.schema(req.database).count({ - where: { ...payload, result: true }, attributes: [[Sequelize.fn('DATE', Sequelize.col('createdAt')), 'Date']], - group: [Sequelize.fn('DATE', Sequelize.col('createdAt')), 'Date'] + group: [Sequelize.fn('DATE', Sequelize.col('createdAt')), 'Date'], + where: { ...payload, result: true } }); const failedHistory = await ExecutionHistory.schema(req.database).count({ - where: { ...payload, result: false }, attributes: [[Sequelize.fn('DATE', Sequelize.col('createdAt')), 'Date']], - group: [Sequelize.fn('DATE', Sequelize.col('createdAt')), 'Date'] + group: [Sequelize.fn('DATE', Sequelize.col('createdAt')), 'Date'], + where: { ...payload, result: false } }); const incompleteHistory = await ExecutionHistory.schema(req.database).count({ - where: { ...payload, result: null }, attributes: [[Sequelize.fn('DATE', Sequelize.col('createdAt')), 'Date']], - group: [Sequelize.fn('DATE', Sequelize.col('createdAt')), 'Date'] + group: [Sequelize.fn('DATE', Sequelize.col('createdAt')), 'Date'], + where: { ...payload, result: null } }); const totalCount = await ExecutionHistory.schema(req.database).count({ where: { executedByUser: req.body.executedByUser || req.user.id } @@ -177,7 +174,7 @@ export const detailedExecutionReport = async (req, res) => { value: (el[1].Incomplete || 0) + (el[1].Failed || 0) + (el[1].Passed || 0) }); }); - return res.status(200).json({ totalCount, data: finalData }); + return res.status(200).json({ data: finalData, totalCount }); } catch (error) { getError(error, res); } diff --git a/Encryption/Controller/aes.controller.js b/Encryption/Controller/aes.controller.js index afb9ece..95d93dc 100644 --- a/Encryption/Controller/aes.controller.js +++ b/Encryption/Controller/aes.controller.js @@ -1,11 +1,14 @@ import getError from '#utils/error.js'; -import { encryptWithAES, decryptWithAES } from '../Service/aes.service.js'; -const encryptData = async (req, res) => { - /* #swagger.tags = ["Encryption"] - #swagger.security = [{"apiKeyAuth": []}] */ +import { decryptWithAES, encryptWithAES } from '../Service/aes.service.js'; + +const encryptData = (req, res) => { + /* + * #swagger.tags = ["Encryption"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const data = req.body.data; + const { data } = req.body; const encrypted = encryptWithAES(data); return res.status(200).json(encrypted); } catch (error) { @@ -13,11 +16,13 @@ const encryptData = async (req, res) => { } }; -const decryptData = async (req, res) => { - /* #swagger.tags = ["Encryption"] - #swagger.security = [{"apiKeyAuth": []}] */ +const decryptData = (req, res) => { + /* + * #swagger.tags = ["Encryption"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const encrypted = req.body.encrypted; + const { encrypted } = req.body; const decrypted = decryptWithAES(encrypted); return res.status(200).json(decrypted); } catch (error) { @@ -25,4 +30,4 @@ const decryptData = async (req, res) => { } }; -export { encryptData, decryptData }; +export { decryptData, encryptData }; diff --git a/Encryption/Routes/aes.routes.js b/Encryption/Routes/aes.routes.js index b376507..3e41326 100644 --- a/Encryption/Routes/aes.routes.js +++ b/Encryption/Routes/aes.routes.js @@ -1,5 +1,6 @@ import express from 'express'; -import { encryptData, decryptData } from '../Controller/aes.controller.js'; + +import { decryptData, encryptData } from '../Controller/aes.controller.js'; const Router = express.Router(); Router.post('/decrypt', decryptData); diff --git a/Encryption/Service/aes.service.js b/Encryption/Service/aes.service.js index 3bde7db..83f7115 100644 --- a/Encryption/Service/aes.service.js +++ b/Encryption/Service/aes.service.js @@ -1,11 +1,12 @@ -import getError from '#utils/error.js'; import crypto from 'crypto'; +import getError from '#utils/error.js'; + const secretKey = 'saranshbalyan123saranshbalyan123'; const initializationVector = 'c3e84932d4eca8d8860e087613ca4313'; // Function to encrypt using AES CBC -function encryptWithAES (text, key = secretKey, iv = initializationVector) { +const encryptWithAES = (text, key = secretKey, iv = initializationVector) => { try { const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), Buffer.from(iv, 'hex')); let encrypted = cipher.update(JSON.stringify(text), 'utf-8', 'hex'); @@ -14,10 +15,10 @@ function encryptWithAES (text, key = secretKey, iv = initializationVector) { } catch (e) { getError(e); } -} +}; // Function to decrypt using AES CBC -function decryptWithAES (encryptedText, key = secretKey, iv = initializationVector) { +const decryptWithAES = (encryptedText, key = secretKey, iv = initializationVector) => { try { const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), Buffer.from(iv, 'hex')); let decrypted = decipher.update(encryptedText, 'hex', 'utf-8'); @@ -26,13 +27,17 @@ function decryptWithAES (encryptedText, key = secretKey, iv = initializationVect } catch (e) { getError(e); } -} +}; -// const plaintext = "Hello, AES CBC encryption!"; -// const encryptedText = encryptWithAES(plaintext, secretKey,initializationVector ); -// console.log("Encrypted:",encryptedText); +/* + * Const plaintext = "Hello, AES CBC encryption!"; + * const encryptedText = encryptWithAES(plaintext, secretKey,initializationVector ); + * console.log("Encrypted:",encryptedText); + */ -// const decryptedText = decryptWithAES("8600ce43592fecadc5b8edba44f0e81a", secretKey, initializationVector); -// console.log("Decrypted:", decryptedText); +/* + * Const decryptedText = decryptWithAES("8600ce43592fecadc5b8edba44f0e81a", secretKey, initializationVector); + * console.log("Decrypted:", decryptedText); + */ -export { encryptWithAES, decryptWithAES }; +export { decryptWithAES, encryptWithAES }; diff --git a/Project/Controllers/projectController.js b/Project/Controllers/projectController.js index e5c4f61..189c7ef 100644 --- a/Project/Controllers/projectController.js +++ b/Project/Controllers/projectController.js @@ -1,8 +1,9 @@ +import errorContstants from '#constants/error.js'; import db from '#utils/dataBaseConnection.js'; import getError from '#utils/error.js'; -import { addProjectValidation, memberProjectValidation, updateProjectValidation } from '../Validations/project.js'; import { idValidation } from '#validations/index.js'; -import errorContstants from '#constants/error.js'; + +import { addProjectValidation, memberProjectValidation, updateProjectValidation } from '../Validations/project.js'; const UserProject = db.userProjects; const Project = db.projects; @@ -11,39 +12,39 @@ const TestCase = db.testCases; const ReusableProcess = db.reusableProcess; const Object = db.objects; const getMyProject = async (req, res) => { - /* #swagger.tags = ["Project"] - #swagger.security = [{"apiKeyAuth": []}] */ + /* + * #swagger.tags = ["Project"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const userId = req.user.id; const { error } = idValidation.validate({ id: userId }); if (error) throw new Error(error.details[0].message); const projects = await UserProject.schema(req.database).findAll({ - where: { userId }, include: [ { - model: Project.schema(req.database), include: [ { - model: UserProject.schema(req.database), as: 'members', include: [ { - model: User.schema(req.database), - attributes: ['id', 'name', 'email', 'active', 'profileImage', 'deletedAt'] + attributes: ['id', 'name', 'email', 'active', 'profileImage', 'deletedAt'], + model: User.schema(req.database) } - ] + ], + model: UserProject.schema(req.database) } - ] + ], + model: Project.schema(req.database) } - ] + ], + where: { userId } }); const updatedArray = projects.map((el) => { const temp = { ...el.project.dataValues }; - temp.members = temp.members.map((el) => { - return el.user; - }); + temp.members = temp.members.map((el1) => el1.user); return temp; }); @@ -54,32 +55,31 @@ const getMyProject = async (req, res) => { }; const getProjectById = async (req, res) => { - /* #swagger.tags = ["Project"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Project"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const projectId = req.params.projectId; + const { projectId } = req.params; const project = await Project.schema(req.database).findByPk(projectId, { attributes: ['id', 'name', 'description', 'startDate', 'endDate', 'createdAt', 'createdByUser'], include: [ { - model: UserProject.schema(req.database), as: 'members', include: [ { - model: User.schema(req.database), - attributes: ['id', 'name', 'email', 'active', 'verifiedAt', 'deletedAt'] + attributes: ['id', 'name', 'email', 'active', 'verifiedAt', 'deletedAt'], + model: User.schema(req.database) } - ] + ], + model: UserProject.schema(req.database) } ] }); const temp = { ...project.dataValues }; - temp.members = temp.members.map((user) => { - return user.dataValues.user; - }); + temp.members = temp.members.map((user) => user.dataValues.user); const testCase = await TestCase.schema(req.database).count({ where: { projectId } @@ -91,16 +91,17 @@ const getProjectById = async (req, res) => { where: { projectId } }); - return res.status(200).json({ ...temp, count: { testCase, reusableProcess, object } }); + return res.status(200).json({ ...temp, count: { object, reusableProcess, testCase } }); } catch (error) { getError(error, res); } }; const addProject = async (req, res) => { - /* #swagger.tags = ["Project"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Project"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { name, description, startDate, endDate } = req.body; @@ -108,17 +109,17 @@ const addProject = async (req, res) => { if (error) throw new Error(error.details[0].message); const project = await Project.schema(req.database).create({ - name, + createdByUser: req.user.id, description, - startDate, endDate, - createdByUser: req.user.id + name, + startDate }); await db.sequelize.query('SET FOREIGN_KEY_CHECKS = 0'); await UserProject.schema(req.database).create({ - userId: req.user.id, - projectId: project.id + projectId: project.id, + userId: req.user.id }); return res.status(200).json(project); @@ -128,11 +129,12 @@ const addProject = async (req, res) => { }; const deleteProject = async (req, res) => { - /* #swagger.tags = ["Project"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Project"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const projectId = req.params.projectId; + const { projectId } = req.params; const hProjectId = req.headers['x-project-id']; if (projectId === hProjectId) throw new Error('Cannot delete current project'); @@ -149,16 +151,17 @@ const deleteProject = async (req, res) => { where: { id: projectId } }); if (deletedProject > 0) return res.status(200).json({ message: 'Project deleted successfully!' }); - else return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (error) { getError(error, res); } }; const addMember = async (req, res) => { - /* #swagger.tags = ["Project"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Project"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { projectId, userId } = req.body; const { error } = memberProjectValidation.validate({ projectId, userId }); @@ -166,8 +169,8 @@ const addMember = async (req, res) => { await db.sequelize.query('SET FOREIGN_KEY_CHECKS = 0'); await UserProject.schema(req.database).create({ - userId, - projectId + projectId, + userId }); return res.status(200).json({ message: 'Project member added!' }); } catch (error) { @@ -176,9 +179,10 @@ const addMember = async (req, res) => { }; const deleteMember = async (req, res) => { - /* #swagger.tags = ["Project"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Project"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { projectId, userId } = req.body; @@ -198,7 +202,7 @@ const deleteMember = async (req, res) => { } ); await UserProject.schema(req.database).destroy({ - where: { userId, projectId } + where: { projectId, userId } }); return res.status(200).json({ message: 'Project member removed!' }); @@ -208,9 +212,10 @@ const deleteMember = async (req, res) => { }; const editProject = async (req, res) => { - /* #swagger.tags = ["Project"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Project"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const projectId = req.headers['x-project-id']; @@ -228,12 +233,11 @@ const editProject = async (req, res) => { if (updatedProject[0]) { return res.status(200).json({ message: 'Project Updated Successfully!' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (error) { getError(error, res); } }; -export { getMyProject, getProjectById, addProject, deleteProject, addMember, deleteMember, editProject }; +export { addMember, addProject, deleteMember, deleteProject, editProject, getMyProject, getProjectById }; diff --git a/Project/Models/Project.js b/Project/Models/Project.js index 4ffd45a..524c585 100644 --- a/Project/Models/Project.js +++ b/Project/Models/Project.js @@ -1,34 +1,34 @@ export default (sequelize, DataTypes) => { const Project = sequelize.define('projects', { - name: { - type: DataTypes.STRING, + createdByUser: { allowNull: false, + references: { + key: 'id', + model: 'users' + }, + type: DataTypes.INTEGER, validate: { notNull: true } }, description: { - type: DataTypes.STRING, - allowNull: true - }, - startDate: { - type: DataTypes.DATEONLY, - allowNull: true + allowNull: true, + type: DataTypes.STRING }, endDate: { - type: DataTypes.DATEONLY, - allowNull: true + allowNull: true, + type: DataTypes.DATEONLY }, - createdByUser: { - type: DataTypes.INTEGER, + name: { allowNull: false, + type: DataTypes.STRING, validate: { notNull: true - }, - references: { - model: 'users', - key: 'id' } + }, + startDate: { + allowNull: true, + type: DataTypes.DATEONLY } }); diff --git a/Project/Models/UserProject.js b/Project/Models/UserProject.js index 48433df..23df643 100644 --- a/Project/Models/UserProject.js +++ b/Project/Models/UserProject.js @@ -1,28 +1,28 @@ export default (sequelize, DataTypes) => { const UserProject = sequelize.define('userProjects', { - userId: { - type: DataTypes.INTEGER, + projectId: { allowNull: false, - validate: { - notNull: true - }, + onDelete: 'CASCADE', references: { - model: 'users', - key: 'id' + key: 'id', + model: 'projects' }, - onDelete: 'CASCADE' - }, - projectId: { type: DataTypes.INTEGER, - allowNull: false, validate: { notNull: true - }, + } + }, + userId: { + allowNull: false, + onDelete: 'CASCADE', references: { - model: 'projects', - key: 'id' + key: 'id', + model: 'users' }, - onDelete: 'CASCADE' + type: DataTypes.INTEGER, + validate: { + notNull: true + } } }); diff --git a/Project/Routes/projectRoutes.js b/Project/Routes/projectRoutes.js index 618d1b3..960c467 100644 --- a/Project/Routes/projectRoutes.js +++ b/Project/Routes/projectRoutes.js @@ -1,6 +1,8 @@ import express from 'express'; -import { getMyProject, getProjectById, addProject, deleteProject, addMember, deleteMember, editProject } from '../Controllers/projectController.js'; + import { validatePermission, validateUserProject } from '#middlewares/permissions.js'; + +import { addMember, addProject, deleteMember, deleteProject, editProject, getMyProject, getProjectById } from '../Controllers/projectController.js'; const Router = express.Router(); Router.get('/', validatePermission('Project', 'view'), getMyProject); diff --git a/Project/Validations/project.js b/Project/Validations/project.js index 264ddd9..c900ca1 100644 --- a/Project/Validations/project.js +++ b/Project/Validations/project.js @@ -1,17 +1,17 @@ import joi from '@hapi/joi'; const addProjectValidation = joi.object({ - name: joi.string().min(3).max(100).required(), description: joi.string().allow(null, '').required(), - startDate: joi.string().required(), - endDate: joi.string().required() + endDate: joi.string().required(), + name: joi.string().min(3).max(100).required(), + startDate: joi.string().required() }); const updateProjectValidation = joi.object({ - name: joi.string().min(3).max(100), description: joi.string().allow(null, '').required(), - startDate: joi.string(), endDate: joi.string(), - projectId: joi.number().integer().required() + name: joi.string().min(3).max(100), + projectId: joi.number().integer().required(), + startDate: joi.string() }); const memberProjectValidation = joi.object({ diff --git a/Routes/constantRoutes.js b/Routes/constantRoutes.js index e8b77b2..ed4ec81 100644 --- a/Routes/constantRoutes.js +++ b/Routes/constantRoutes.js @@ -1,5 +1,6 @@ import express from 'express'; -import { getAllPermission, getAllActionEvent } from '../Controllers/constantController.js'; + +import { getAllActionEvent, getAllPermission } from '../Controllers/constantController.js'; const Router = express.Router(); Router.get('/permission', getAllPermission); Router.get('/actionEvent', getAllActionEvent); diff --git a/Routes/dashboardRoutes.js b/Routes/dashboardRoutes.js index 977d132..9ee130a 100644 --- a/Routes/dashboardRoutes.js +++ b/Routes/dashboardRoutes.js @@ -1,5 +1,6 @@ import express from 'express'; -import { dashboard, detailedExecutionReport, executionReport, createdReport } from '../Controllers/dashboardController.js'; + +import { createdReport, dashboard, detailedExecutionReport, executionReport } from '../Controllers/dashboardController.js'; const Router = express.Router(); Router.get('/', dashboard); Router.post('/detailed-execution-report', detailedExecutionReport); diff --git a/Routes/index.js b/Routes/index.js index 8998bec..9a7f2a9 100644 --- a/Routes/index.js +++ b/Routes/index.js @@ -1,6 +1,7 @@ import { validateToken } from '#middlewares/jwt.js'; -import unprotectedRoutes from './unprotectedRoutes.js'; + import protectedRoutes from './protectedRoutes.js'; +import unprotectedRoutes from './unprotectedRoutes.js'; const registerUnprotectedRoutes = (app) => { unprotectedRoutes.forEach((route) => { @@ -21,4 +22,4 @@ const registerRoutes = (app) => { console.success('Routes Registered'); }; -export { registerRoutes }; +export default registerRoutes; diff --git a/Routes/protectedRoutes.js b/Routes/protectedRoutes.js index 94bf01a..e310f51 100644 --- a/Routes/protectedRoutes.js +++ b/Routes/protectedRoutes.js @@ -1,37 +1,37 @@ -import userRoutes from '#user/Routes/userRoutes.js'; -import superAdminRoutes from '#user/Routes/superAdminRoutes.js'; -import roleRoutes from '#user/Routes/roleRoutes.js'; import projectRoutes from '#project/Routes/projectRoutes.js'; -import testCaseRoutes from '#testcase/Routes/testCase.js'; -import objectRoutes from '#testcase/Routes/object.js'; -import testStepRoutes from '#testcase/Routes/testStepRoutes.js'; -import reusableProcessRoutes from '#testcase/Routes/reusableProcess.js'; +import constantRoutes from '#root/Routes/constantRoutes.js'; +import dashboardRoutes from '#routes/dashboardRoutes.js'; +import storageRoutes from '#storage/Routes/awsRoutes.js'; +import environmentRoutes from '#testcase/Routes/environment.js'; import executionHistoryRoutes from '#testcase/Routes/executionHistory.js'; import executionSuiteRoutes from '#testcase/Routes/executionSuiteRoutes.js'; -import environmentRoutes from '#testcase/Routes/environment.js'; -import storageRoutes from '#storage/Routes/awsRoutes.js'; import machineRoutes from '#testcase/Routes/machineRoutes.js'; -import dashboardRoutes from '#routes/dashboardRoutes.js'; -import constantRoutes from '#root/Routes/constantRoutes.js'; -// import schedulerRoutes from "#scheduler/Routes/schedulerRoutes.js"; +import objectRoutes from '#testcase/Routes/object.js'; +import reusableProcessRoutes from '#testcase/Routes/reusableProcess.js'; +import testCaseRoutes from '#testcase/Routes/testCase.js'; +import testStepRoutes from '#testcase/Routes/testStepRoutes.js'; +import roleRoutes from '#user/Routes/roleRoutes.js'; +import superAdminRoutes from '#user/Routes/superAdminRoutes.js'; +import userRoutes from '#user/Routes/userRoutes.js'; +// Import schedulerRoutes from "#scheduler/Routes/schedulerRoutes.js"; const protectedRoutes = [ - { path: '/constant', list: constantRoutes }, + { list: constantRoutes, path: '/constant' }, // { path: "/scheduler", list: schedulerRoutes }, - { path: '/user', list: userRoutes }, - { path: '/super-admin', list: superAdminRoutes }, - { path: '/role', list: roleRoutes }, - { path: '/project', list: projectRoutes }, - { path: '/dashboard', list: dashboardRoutes }, - { path: '/storage', list: storageRoutes }, - { path: '/testcase', list: testCaseRoutes }, - { path: '/object', list: objectRoutes }, - { path: '/teststep', list: testStepRoutes }, - { path: '/reusableProcess', list: reusableProcessRoutes }, - { path: '/executionHistory', list: executionHistoryRoutes }, - { path: '/environment', list: environmentRoutes }, - { path: '/machines', list: machineRoutes }, - { path: '/execution-suite', list: executionSuiteRoutes } + { list: userRoutes, path: '/user' }, + { list: superAdminRoutes, path: '/super-admin' }, + { list: roleRoutes, path: '/role' }, + { list: projectRoutes, path: '/project' }, + { list: dashboardRoutes, path: '/dashboard' }, + { list: storageRoutes, path: '/storage' }, + { list: testCaseRoutes, path: '/testcase' }, + { list: objectRoutes, path: '/object' }, + { list: testStepRoutes, path: '/teststep' }, + { list: reusableProcessRoutes, path: '/reusableProcess' }, + { list: executionHistoryRoutes, path: '/executionHistory' }, + { list: environmentRoutes, path: '/environment' }, + { list: machineRoutes, path: '/machines' }, + { list: executionSuiteRoutes, path: '/execution-suite' } ]; export default protectedRoutes; diff --git a/Routes/rootRoutes.js b/Routes/rootRoutes.js index e0aeedd..a1873b3 100644 --- a/Routes/rootRoutes.js +++ b/Routes/rootRoutes.js @@ -1,18 +1,17 @@ import express from 'express'; -import swaggerUi from 'swagger-ui-express'; - -// swagger +// Swagger import { createRequire } from 'module'; +import swaggerUi from 'swagger-ui-express'; const require = createRequire(import.meta.url); const swaggerFile = require('../swagger.json'); -// swagger +// Swagger const Router = express.Router(); -Router.get('/health', (req, res) => { +Router.get('/health', (req, res) => /* #swagger.tags = ["Health"] */ - return res.json('Server is Working'); -}); + res.json('Server is Working') +); Router.use('/swagger', swaggerUi.serve); Router.get('/swagger', swaggerUi.setup(swaggerFile)); diff --git a/Routes/unprotectedRoutes.js b/Routes/unprotectedRoutes.js index b084807..015cae4 100644 --- a/Routes/unprotectedRoutes.js +++ b/Routes/unprotectedRoutes.js @@ -1,12 +1,12 @@ -import authRoutes from '#user/Routes/authRoutes.js'; -import rootRoutes from '#routes/rootRoutes.js'; import aesRoutes from '#encryption/Routes/aes.routes.js'; +import rootRoutes from '#routes/rootRoutes.js'; +import authRoutes from '#user/Routes/authRoutes.js'; import passportRoutes from '#user/Routes/passport.js'; const unprotectedRoutes = [ - { path: '/auth', list: authRoutes }, - { path: '/', list: rootRoutes }, - { path: '/encryption/aes', list: aesRoutes }, - { path: '/auth', list: passportRoutes } + { list: authRoutes, path: '/auth' }, + { list: rootRoutes, path: '/' }, + { list: aesRoutes, path: '/encryption/aes' }, + { list: passportRoutes, path: '/auth' } ]; export default unprotectedRoutes; diff --git a/Scheduler/Controllers/jobController.js b/Scheduler/Controllers/jobController.js index 0af2931..446c0b0 100644 --- a/Scheduler/Controllers/jobController.js +++ b/Scheduler/Controllers/jobController.js @@ -1,22 +1,26 @@ +import errorContstants from '#constants/error.js'; +import successContstants from '#constants/success.js'; import db from '#utils/dataBaseConnection.js'; import getError from '#utils/error.js'; import { idValidation } from '#validations/index.js'; -// import { createJobValidataion } from "../Validations/scheduler.js"; -import errorContstants from '#constants/error.js'; -import successContstants from '#constants/success.js'; -import { addJob, updateJobStatus, getJobManagerFromMap } from '../Service/schedulerService.js'; + +// Import { createJobValidataion } from "../Validations/scheduler.js"; +import { addJob, getJobManagerFromMap, updateJobStatus } from '../Service/schedulerService.js'; const Job = db.jobs; const JobManager = db.jobManagers; export const createJob = async (req, res) => { - /* #swagger.tags = ["Scheduler"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Scheduler"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - // const { error } = createJobValidataion.validate(req.body); - // if (error) throw new Error(error.details[0].message); + /* + * Const { error } = createJobValidataion.validate(req.body); + * if (error) throw new Error(error.details[0].message); + */ - const jobManagerId = req.body.jobManagerId; + const { jobManagerId } = req.body; const job = await Job.schema(req.database).create({ ...req.body }); await addJob(jobManagerId, job, req.user.tenant); return res.status(200).json(job); @@ -26,11 +30,12 @@ export const createJob = async (req, res) => { }; export const updateJob = async (req, res) => { - /* #swagger.tags = ["Scheduler"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Scheduler"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const jobId = req.params.jobId; + const { jobId } = req.params; const { error } = idValidation.validate({ id: jobId }); if (error) throw new Error(error.details[0].message); @@ -38,7 +43,7 @@ export const updateJob = async (req, res) => { if (!job) return res.status(404).json({ error: errorContstants.RECORD_NOT_FOUND }); const updatedJob = await Job.schema(req.database).update({ ...req.body }, { where: { id: jobId } }); - if (Object.prototype.hasOwnProperty.call(req.body, 'active')) updateJobStatus(job.jobManagerId, jobId, req.body.active, req.user.tenant); + if (Object.hasOwn(req.body, 'active')) updateJobStatus(job.jobManagerId, jobId, req.body.active, req.user.tenant); if (updatedJob.length > 0) return res.status(200).json({ message: successContstants.UPDATED }); } catch (error) { @@ -47,11 +52,12 @@ export const updateJob = async (req, res) => { }; export const getAllJobByJobManagerId = async (req, res) => { - /* #swagger.tags = ["Scheduler"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Scheduler"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const jobManagerId = req.params.jobManagerId; + const { jobManagerId } = req.params; const jobs = await Job.schema(req.database).findAll({ where: { jobManagerId } }); return res.status(200).json(jobs); } catch (error) { @@ -60,11 +66,12 @@ export const getAllJobByJobManagerId = async (req, res) => { }; export const getJobById = async (req, res) => { - /* #swagger.tags = ["Scheduler"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Scheduler"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const jobId = req.params.jobId; + const { jobId } = req.params; const job = await Job.schema(req.database).findByPk(jobId); return res.status(200).json(job); } catch (error) { @@ -73,15 +80,16 @@ export const getJobById = async (req, res) => { }; export const removeJob = async (req, res) => { - /* #swagger.tags = ["Scheduler"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Scheduler"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const jobId = req.params.jobId; + const { jobId } = req.params; const manager = await JobManager.findOne({ where: { jobId } }); - const jobManager = getJobManagerFromMap(req.user.tenant + '_' + manager.id); + const jobManager = getJobManagerFromMap(`${req.user.tenant}_${manager.id}`); await jobManager.stop(String(jobId)); const { error } = idValidation.validate({ id: jobId }); if (error) throw new Error(error.details[0].message); @@ -90,7 +98,7 @@ export const removeJob = async (req, res) => { where: { id: jobId } }); if (deletedJob > 0) return res.status(200).json({ message: successContstants.DELETED }); - else return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (error) { getError(error, res); } diff --git a/Scheduler/Controllers/jobManagerController.js b/Scheduler/Controllers/jobManagerController.js index 63bed77..e436ea1 100644 --- a/Scheduler/Controllers/jobManagerController.js +++ b/Scheduler/Controllers/jobManagerController.js @@ -1,21 +1,26 @@ +import _ from 'lodash'; + +import errorContstants from '#constants/error.js'; +import successContstants from '#constants/success.js'; import db from '#utils/dataBaseConnection.js'; import getError from '#utils/error.js'; import { idValidation } from '#validations/index.js'; -// import { createJobManagerValidation } from "../Validations/scheduler.js"; -import errorContstants from '#constants/error.js'; -import successContstants from '#constants/success.js'; -import _ from 'lodash'; -import { stopManager, startManagerJobs, addToConnectionPool, deleteFromConnectionPool, getJobManagerFromMap } from '../Service/schedulerService.js'; + +// Import { createJobManagerValidation } from "../Validations/scheduler.js"; +import { addToConnectionPool, deleteFromConnectionPool, getJobManagerFromMap, startManagerJobs, stopManager } from '../Service/schedulerService.js'; const JobManager = db.jobManagers; const Job = db.jobs; export const createJobManager = async (req, res) => { - /* #swagger.tags = ["Scheduler"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Scheduler"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - // const { error } = createJobManagerValidation.validate(req.body); - // if (error) throw new Error(error.details[0].message); + /* + * Const { error } = createJobManagerValidation.validate(req.body); + * if (error) throw new Error(error.details[0].message); + */ const projectId = req.headers['x-project-id']; const { active, connection } = req.body; @@ -32,11 +37,12 @@ export const createJobManager = async (req, res) => { }; export const updateJobManagerById = async (req, res) => { - /* #swagger.tags = ["Scheduler"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Scheduler"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const jobManagerId = req.params.jobManagerId; + const { jobManagerId } = req.params; const { error } = idValidation.validate({ id: jobManagerId }); if (error) throw new Error(error.details[0].message); @@ -49,12 +55,12 @@ export const updateJobManagerById = async (req, res) => { if (active) { if (prevJobManager.dataValues.active === false) { - console.log('Starting Job Manager: ' + prevJobManager.dataValues.id); + console.log(`Starting Job Manager: ${prevJobManager.dataValues.id}`); const jobs = await Job.schema(req.database).findAll({ where: { jobManagerId } }); - await startManagerJobs({ name, active, connection, jobs }, req.user.tenant, false); + await startManagerJobs({ active, connection, jobs, name }, req.user.tenant, false); } else { console.log('Job Manager already active'); - const { host, port, dialect, user, password, db } = connection; + const { host, port, dialect, user, password, db: database } = connection; if ( (host && port && dialect && user && password) || prevConnectionData.host !== host || @@ -62,10 +68,10 @@ export const updateJobManagerById = async (req, res) => { prevConnectionData.dialect !== dialect || prevConnectionData.user !== user || prevConnectionData.password !== password || - prevConnectionData.db !== db + prevConnectionData.db !== database ) { console.log('New Connection Found'); - deleteFromConnectionPool(req.user.tenant + '_' + prevJobManager.dataValues.id); + deleteFromConnectionPool(`${req.user.tenant}_${prevJobManager.dataValues.id}`); await addToConnectionPool(jobManagerId, req.user.tenant, req.body.connection); } else { console.log('Using Old Connection'); @@ -75,7 +81,7 @@ export const updateJobManagerById = async (req, res) => { } else { console.log('Making Job Manager Inactive'); if (prevJobManager.dataValues.active === true) { - const oldJobManager = getJobManagerFromMap(req.user.tenant + '_' + prevJobManager.dataValues.id); + const oldJobManager = getJobManagerFromMap(`${req.user.tenant}_${prevJobManager.dataValues.id}`); if (oldJobManager) { stopManager(prevJobManager.dataValues.id, req.user.tenant); console.log('Job Manager Inactive Successfully'); @@ -85,9 +91,11 @@ export const updateJobManagerById = async (req, res) => { const updatedJobManager = await JobManager.schema(req.database).update(payload, { where: { id: jobManagerId } }); if (updatedJobManager.length > 0) { - // console.log(Updated Scheduler Maps") - // console.log("Connection Pool: ", connectionPool) - // console.log("Job Manager: ", jobManagerMap,") + /* + * Console.log(Updated Scheduler Maps") + * console.log("Connection Pool: ", connectionPool) + * console.log("Job Manager: ", jobManagerMap,") + */ return res.status(200).json({ message: successContstants.UPDATED }); } } catch (error) { @@ -96,9 +104,10 @@ export const updateJobManagerById = async (req, res) => { }; export const getAllJobManager = async (req, res) => { - /* #swagger.tags = ["Scheduler"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Scheduler"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const projectId = req.headers['x-project-id']; const jobManagers = await JobManager.schema(req.database).findAll({ where: { projectId } }); @@ -109,11 +118,12 @@ export const getAllJobManager = async (req, res) => { }; export const getJobManagerById = async (req, res) => { - /* #swagger.tags = ["Scheduler"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Scheduler"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const jobManagerId = req.params.jobManagerId; + const { jobManagerId } = req.params; const jobManager = await JobManager.schema(req.database).findByPk(jobManagerId); return res.status(200).json(jobManager); } catch (error) { @@ -122,11 +132,12 @@ export const getJobManagerById = async (req, res) => { }; export const removeJobManager = async (req, res) => { - /* #swagger.tags = ["Scheduler"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Scheduler"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const jobManagerId = req.params.jobManagerId; + const { jobManagerId } = req.params; const { error } = idValidation.validate({ id: jobManagerId }); if (error) throw new Error(error.details[0].message); @@ -134,7 +145,7 @@ export const removeJobManager = async (req, res) => { where: { id: jobManagerId } }); if (deletedJobManager > 0) return res.status(200).json({ message: successContstants.DELETED }); - else return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (error) { getError(error, res); } diff --git a/Scheduler/Models/JobManager.js b/Scheduler/Models/JobManager.js index cabee46..d2a43bc 100644 --- a/Scheduler/Models/JobManager.js +++ b/Scheduler/Models/JobManager.js @@ -1,49 +1,49 @@ import { createToken, decryptJwt } from '#utils/jwt.js'; export default (sequelize, DataTypes) => { const JobManager = sequelize.define('jobManagers', { - name: { - type: DataTypes.STRING, - allowNull: false, - validate: { - notNull: true - } - }, active: { - type: DataTypes.BOOLEAN, defaultValue: 1, + type: DataTypes.BOOLEAN, values: [0, 1] }, - projectId: { - type: DataTypes.INTEGER, - allowNull: true, - default: null - }, connection: { - type: DataTypes.TEXT, allowNull: true, - set (value) { - this.setDataValue('connection', createToken(value, process.env.JWT_ACCESS_SECRET)); - }, get () { const token = this.getDataValue('connection'); return token ? decryptJwt(token) : null; - } + }, + set (value) { + this.setDataValue('connection', createToken(value, process.env.JWT_ACCESS_SECRET)); + }, + type: DataTypes.TEXT }, decryptionAllowed: { - type: DataTypes.BOOLEAN, defaultValue: 0, + type: DataTypes.BOOLEAN, values: [0, 1] }, kmsData: { - type: DataTypes.JSON, allowNull: true, - set (value) { - this.setDataValue('kmsData', createToken(value, process.env.JWT_ACCESS_SECRET)); - }, get () { const token = this.getDataValue('kmsData'); return token ? decryptJwt(token) : null; + }, + set (value) { + this.setDataValue('kmsData', createToken(value, process.env.JWT_ACCESS_SECRET)); + }, + type: DataTypes.JSON + }, + name: { + allowNull: false, + type: DataTypes.STRING, + validate: { + notNull: true } + }, + projectId: { + allowNull: true, + default: null, + type: DataTypes.INTEGER } }); diff --git a/Scheduler/Models/job.js b/Scheduler/Models/job.js index 00c19d0..9f40a23 100644 --- a/Scheduler/Models/job.js +++ b/Scheduler/Models/job.js @@ -1,51 +1,51 @@ export default (sequelize, DataTypes) => { const Job = sequelize.define('jobs', { - name: { + active: { + defaultValue: 1, + type: DataTypes.BOOLEAN, + values: [0, 1] + }, + decryptColumn: { + defaultValue: null, + type: DataTypes.STRING + }, + extension: { + defaultValue: null, type: DataTypes.STRING, + values: ['txt', 'csv', 'json', 'xlsx'] + }, + jobManagerId: { allowNull: false, + type: DataTypes.INTEGER, validate: { notNull: true } }, - jobManagerId: { - type: DataTypes.INTEGER, + name: { allowNull: false, + type: DataTypes.STRING, validate: { notNull: true } }, + query: { + defaultValue: null, + type: DataTypes.STRING + }, time: { - type: DataTypes.STRING, - defaultValue: '0 5 31 2 *' + defaultValue: '0 5 31 2 *', + type: DataTypes.STRING + }, + timezone: { + defaultValue: 'Asia/Kolkata', + type: DataTypes.STRING }, type: { - type: DataTypes.STRING, allowNull: false, + type: DataTypes.STRING, validate: { notNull: true } - }, - timezone: { - type: DataTypes.STRING, - defaultValue: 'Asia/Kolkata' - }, - active: { - type: DataTypes.BOOLEAN, - defaultValue: 1, - values: [0, 1] - }, - query: { - type: DataTypes.STRING, - defaultValue: null - }, - decryptColumn: { - type: DataTypes.STRING, - defaultValue: null - }, - extension: { - type: DataTypes.STRING, - defaultValue: null, - values: ['txt', 'csv', 'json', 'xlsx'] } }); diff --git a/Scheduler/Routes/schedulerRoutes.js b/Scheduler/Routes/schedulerRoutes.js index 686c856..4dfd07c 100644 --- a/Scheduler/Routes/schedulerRoutes.js +++ b/Scheduler/Routes/schedulerRoutes.js @@ -1,7 +1,7 @@ import express from 'express'; -import { getAllJobManager, createJobManager, removeJobManager, getJobManagerById, updateJobManagerById } from '../Controllers/jobManagerController.js'; -import { getAllJobByJobManagerId, createJob, removeJob, getJobById, updateJob } from '../Controllers/jobController.js'; +import { createJob, getAllJobByJobManagerId, getJobById, removeJob, updateJob } from '../Controllers/jobController.js'; +import { createJobManager, getAllJobManager, getJobManagerById, removeJobManager, updateJobManagerById } from '../Controllers/jobManagerController.js'; const Router = express.Router(); Router.get('/job-manager', getAllJobManager); diff --git a/Scheduler/Service/jobRunner.js b/Scheduler/Service/jobRunner.js index 4804cbf..29efd08 100644 --- a/Scheduler/Service/jobRunner.js +++ b/Scheduler/Service/jobRunner.js @@ -9,7 +9,7 @@ export const executeQuery = async (connection, job) => { if (extension) { generateFile(results, name, extension); } - // console.timeEnd() + // Console.timeEnd() } catch (err) { console.log(err); } @@ -19,7 +19,7 @@ export const executeCurl = (curl) => { console.log('Executing Curl ', curl); }; -function formatJSON (data, extension) { +const formatJSON = (data, extension) => { if (extension === 'json') { return JSON.stringify(data); } @@ -28,13 +28,13 @@ function formatJSON (data, extension) { const csv = formatterData.map((row) => Object.values(row)); csv.unshift(Object.keys(data[0])); return csv.join('\n'); - } else return JSON.stringify(data); -} + } return JSON.stringify(data); +}; const generateFile = (data, name, extension) => { - const fileName = `${name ? name + '_' + new Date().toISOString() : new Date().toISOString()}.${extension[0] === '.' ? extension.slice(1) : extension}`; - console.log('Generating file with name: ' + fileName); - const outputPath = './Resource/Reports/' + fileName; + const fileName = `${name ? `${name}_${new Date().toISOString()}` : new Date().toISOString()}.${extension[0] === '.' ? extension.slice(1) : extension}`; + console.log(`Generating file with name: ${fileName}`); + const outputPath = `./Resource/Reports/${fileName}`; try { if (extension === 'xlsx') { @@ -42,11 +42,10 @@ const generateFile = (data, name, extension) => { const workBook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workBook, workSheet, 'Report'); return XLSX.writeFile(workBook, outputPath); - } else { - const output = fs.createWriteStream(outputPath, { encoding: 'utf8' }); - output.write(formatJSON(data, extension)); - return output.end(); } + const output = fs.createWriteStream(outputPath, { encoding: 'utf8' }); + output.write(formatJSON(data, extension)); + return output.end(); } catch (err) { console.log(err); } diff --git a/Scheduler/Service/schedulerService.js b/Scheduler/Service/schedulerService.js index 934b63c..581886d 100644 --- a/Scheduler/Service/schedulerService.js +++ b/Scheduler/Service/schedulerService.js @@ -1,6 +1,8 @@ import Scheduler from 'cron-job-manager'; -import db, { createDBConnection } from '#utils/dataBaseConnection.js'; + import { getAllTenant } from '#user/Service/database.js'; +import db, { createDBConnection } from '#utils/dataBaseConnection.js'; + import { executeCurl, executeQuery } from './jobRunner.js'; const JobManager = db.jobManagers; const Job = db.jobs; @@ -26,7 +28,7 @@ export const scheduleInit = async () => { await startManagerJobs(manager, customer.tenantName); } } - // console.log("Connection Pool: ", console.log(connectionPool)) + // Console.log("Connection Pool: ", console.log(connectionPool)) console.log('Current Jobs', jobManagerMap); } catch (e) { console.error(e); @@ -41,7 +43,7 @@ export const startManagerJobs = async (manager, tenant) => { console.log('Starting Manager Connection'); await addToConnectionPool(manager.id, tenant, manager.connection); } else console.log('No Connection Found'); - jobManagerMap[tenant + '_' + manager.id] = new Scheduler(); + jobManagerMap[`${tenant}_${manager.id}`] = new Scheduler(); manager.jobs?.forEach((job) => { addJob(manager.id, job, tenant); @@ -53,10 +55,10 @@ export const startManagerJobs = async (manager, tenant) => { export const stopManager = async (managerId, tenant) => { try { - const manager = jobManagerMap[tenant + '_' + managerId]; + const manager = jobManagerMap[`${tenant}_${managerId}`]; await manager.stopAll(); - delete connectionPool[tenant + '_' + managerId]; - delete jobManagerMap[tenant + '_' + managerId]; + delete connectionPool[`${tenant}_${managerId}`]; + delete jobManagerMap[`${tenant}_${managerId}`]; } catch (err) { console.error(err); } @@ -64,7 +66,7 @@ export const stopManager = async (managerId, tenant) => { export const addJob = async (managerId, job, tenant) => { try { - const manager = jobManagerMap[tenant + '_' + managerId]; + const manager = jobManagerMap[`${tenant}_${managerId}`]; return await manager.add( String(job.id), @@ -73,7 +75,7 @@ export const addJob = async (managerId, job, tenant) => { console.log('Job Triggered:', job.name); switch (job.type) { case 'query': - executeQuery(connectionPool[tenant + '_' + managerId], job); + executeQuery(connectionPool[`${tenant}_${managerId}`], job); break; case 'curl': executeCurl(job.data); @@ -83,11 +85,11 @@ export const addJob = async (managerId, job, tenant) => { } }, { - start: job.active, - timeZone: job.timezone, onComplete: () => { console.log('Job Stopped:', job.name); - } + }, + start: job.active, + timeZone: job.timezone } ); } catch (err) { @@ -97,7 +99,7 @@ export const addJob = async (managerId, job, tenant) => { export const addToConnectionPool = async (managerId, tenant, connection) => { try { - connectionPool[tenant + '_' + managerId] = await createDBConnection(connection); + connectionPool[`${tenant}_${managerId}`] = await createDBConnection(connection); return true; } catch (err) { console.error(err); @@ -132,7 +134,7 @@ export const updateJobStatus = (managerId, jobId, status, tenant) => { if (status !== true && status !== false) return console.log('Invalid Job Status'); console.log(`Updating Job with key ${jobId} status to ${status}:`); try { - const manager = jobManagerMap[tenant + '_' + managerId]; + const manager = jobManagerMap[`${tenant}_${managerId}`]; if (status === true) { manager.start(String(jobId)); } else if (status === false) { diff --git a/Scheduler/Validations/scheduler.js b/Scheduler/Validations/scheduler.js index caeab03..0a00f2c 100644 --- a/Scheduler/Validations/scheduler.js +++ b/Scheduler/Validations/scheduler.js @@ -1,19 +1,19 @@ import joi from '@hapi/joi'; const createJobManagerValidation = joi.object({ - name: joi.string().min(1).max(10).required(), active: joi.boolean(), - connection: joi.object().allow(null, '') + connection: joi.object().allow(null, ''), + name: joi.string().min(1).max(10).required() }); const createJobValidataion = joi.object({ - name: joi.string().min(1).max(10).required(), + active: joi.boolean(), + data: joi.object().allow(null, ''), jobManagerId: joi.number().integer().required(), - type: joi.string().required(), + name: joi.string().min(1).max(10).required(), time: joi.string().required(), - data: joi.object().allow(null, ''), timezone: joi.string(), - active: joi.boolean() + type: joi.string().required() }); export { createJobManagerValidation, createJobValidataion }; diff --git a/Storage/Controllers/awsController.js b/Storage/Controllers/awsController.js index 3328685..a9bf4af 100644 --- a/Storage/Controllers/awsController.js +++ b/Storage/Controllers/awsController.js @@ -1,10 +1,12 @@ import errorContstants from '#constants/error.js'; + import { getAwsObject } from '../Service/awsService.js'; export const getObject = async (req, res) => { - /* #swagger.tags = ["AWS"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["AWS"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const data = await getAwsObject(req.database.split('_')[1], req.body.fileName); diff --git a/Storage/Routes/awsRoutes.js b/Storage/Routes/awsRoutes.js index 719d336..f7ccfe9 100644 --- a/Storage/Routes/awsRoutes.js +++ b/Storage/Routes/awsRoutes.js @@ -1,4 +1,5 @@ import express from 'express'; + import { getObject } from '../Controllers/awsController.js'; const Router = express.Router(); Router.post('/object', getObject); diff --git a/Storage/Service/awsService.js b/Storage/Service/awsService.js index e1ec930..7695fc3 100644 --- a/Storage/Service/awsService.js +++ b/Storage/Service/awsService.js @@ -1,18 +1,19 @@ -import { Upload } from '@aws-sdk/lib-storage'; import { S3 } from '@aws-sdk/client-s3'; +import { Upload } from '@aws-sdk/lib-storage'; + import errorContstants from '#constants/error.js'; export const s3 = new S3({ - region: 'ap-south-1', credentials: { accessKeyId: '', secretAccessKey: '' - } + }, + region: 'ap-south-1' }); export const listBuckets = () => { try { - s3.listBuckets(function (err, data) { + s3.listBuckets((err, data) => { if (err) throw new Error(err); return data.Buckets; }); @@ -28,9 +29,9 @@ export const uploadFile = async (file, bucketName, keyName) => { if (!keyName || !file) throw new Error(errorContstants.INVALID_FILE); const uploadParams = { + Body: file.data, Bucket: bucketName.toLowerCase(), - Key: keyName, - Body: file.data + Key: keyName }; return await new Upload({ @@ -52,7 +53,7 @@ export const createBucket = (bucketName) => { } }; - s3.createBucket(bucketParams, function (err, data) { + s3.createBucket(bucketParams, (err, data) => { if (err) { console.error('Failed to create s3 bucket', err); } else { @@ -73,7 +74,7 @@ export const deleteBucket = (bucketName) => { Bucket: bucketName.toLowerCase() }; - s3.deleteBucket(bucketParams, function (err) { + s3.deleteBucket(bucketParams, (err) => { if (err) { console.error(`Failed to delete s3 bucket ${bucketName.toLowerCase()}`); console.error(err); @@ -94,7 +95,7 @@ export const listObjectsInBucket = (bucketName) => { Bucket: bucketName.toLowerCase() }; - s3.listObjects(bucketParams, function (err, data) { + s3.listObjects(bucketParams, (err, data) => { if (err) throw new Error(err); return data; }); @@ -111,7 +112,7 @@ export const deleteObject = (bucketName, key) => { s3.deleteObject({ Bucket: bucketName.toLowerCase(), key }, (err) => { if (err) return false; - else return true; + return true; }); } catch (err) { console.error('Unable to delete S3 Object', err); @@ -148,10 +149,10 @@ export const deleteS3Folder = (bucketName, folderName) => { let params = { Bucket: bucketName.toLowerCase(), - Prefix: folderName + '/' + Prefix: `${folderName}/` }; try { - s3.listObjects(params, function (err, data) { + s3.listObjects(params, (err, data) => { if (err) return console.log(err); if (data.Contents.length === 0) return; @@ -159,15 +160,15 @@ export const deleteS3Folder = (bucketName, folderName) => { params = { Bucket: bucketName }; params.Delete = { Objects: [] }; - data.Contents.forEach(function (content) { + data.Contents.forEach((content) => { params.Delete.Objects.push({ Key: content.Key }); }); - s3.deleteObjects(params, function (err, data) { - if (err) return console.log(err); - if (data.Errors?.length > 0) { + s3.deleteObjects(params, (err1, data1) => { + if (err1) return console.log(err1); + if (data1.Errors?.length > 0) { console.log('Error in Deleting S3 Files'); - console.log(data.Errors); + console.log(data1.Errors); } }); }); diff --git a/Test/Api/auth.js b/Test/Api/auth.js index fc896d7..d3ca864 100644 --- a/Test/Api/auth.js +++ b/Test/Api/auth.js @@ -5,8 +5,8 @@ axios.defaults.baseURL = `http://localhost:${process.env.PORT || 3001}`; const register = async (config) => { try { const payload = { - name: config.name, email: config.email, + name: config.name, password: config.password }; console.debug('Registering with payload', payload); @@ -63,7 +63,7 @@ const deleteCustomerByAdmin = async (config) => { } }; -export { register, login, deleteCustomerByAdmin, verifyCustomer }; +export { deleteCustomerByAdmin, login, register, verifyCustomer }; const getSuperAdminToken = async () => { try { diff --git a/Test/Api/index.js b/Test/Api/index.js index 8f94d56..a661d83 100644 --- a/Test/Api/index.js +++ b/Test/Api/index.js @@ -1,9 +1,9 @@ -import { register, login, deleteCustomerByAdmin, verifyCustomer } from './auth.js'; -// import { deleteCustomer } from "#user/Service/database.js"; +import { deleteCustomerByAdmin, login, register, verifyCustomer } from './auth.js'; +// Import { deleteCustomer } from "#user/Service/database.js"; const config = { - name: 'Api Test', email: 'saranshbalyan123@gmail.com', + name: 'Api Test', password: 'ysoserious123' }; @@ -21,7 +21,7 @@ const apiTest = async () => { const loginResult = await login(config); if (!loginResult) throw new Error('Login Failed'); } catch (e) { - // deleteCustomerByAdmin(config); + // DeleteCustomerByAdmin(config); } finally { deleteCustomerByAdmin(config); } diff --git a/TestCase/Controllers/environment.js b/TestCase/Controllers/environment.js index bf07971..8609665 100644 --- a/TestCase/Controllers/environment.js +++ b/TestCase/Controllers/environment.js @@ -1,15 +1,17 @@ +import errorContstants from '#constants/error.js'; import db from '#utils/dataBaseConnection.js'; import getError from '#utils/error.js'; import { idValidation } from '#validations/index.js'; + import { nameTestCaseId, updateColumnValidation } from '../Validations/environment.js'; -import errorContstants from '#constants/error.js'; const Environment = db.enviroments; const Column = db.columns; const createEnvironment = async (req, res) => { - /* #swagger.tags = ["Environment"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Environment"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { await db.sequelize.transaction(async (transaction) => { @@ -20,10 +22,10 @@ const createEnvironment = async (req, res) => { const env = await Environment.schema(req.database).create(payload, { transaction }); const enviroment = await Environment.schema(req.database).findOne({ + attributes: ['id'], where: { testCaseId: payload.testCaseId - }, - attributes: ['id'] + } }); if (enviroment) { @@ -31,9 +33,7 @@ const createEnvironment = async (req, res) => { where: { envId: enviroment.id } }); - const columnPayload = columns.map((el) => { - return { value: null, envId: env.id, name: el.dataValues.name }; - }); + const columnPayload = columns.map((el) => ({ envId: env.id, name: el.dataValues.name, value: null })); await Column.schema(req.database).bulkCreate(columnPayload, { transaction }); } @@ -44,36 +44,38 @@ const createEnvironment = async (req, res) => { } }; const getAllEnvironmentsByTestCase = async (req, res) => { - /* #swagger.tags = ["Environment"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Environment"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const testCaseId = req.params.testCaseId; + const { testCaseId } = req.params; const { error } = idValidation.validate({ id: testCaseId }); if (error) throw new Error(error.details[0].message); const enviroments = await Environment.schema(req.database).findAll({ - where: { - testCaseId - }, attributes: ['id', 'name'], include: [ { - model: Column.schema(req.database), - attributes: ['name', 'value'] + attributes: ['name', 'value'], + model: Column.schema(req.database) } - ] + ], + where: { + testCaseId + } }); const env = enviroments.map((el) => { const temp = el.dataValues.columns; const newKeys = {}; - temp.forEach((el) => { - newKeys[el.name] = el.value; + + temp.forEach((el1) => { + newKeys[el1.name] = el1.value; }); return { - envId: el.dataValues.id, Environment: el.dataValues.name, + envId: el.dataValues.id, ...newKeys }; }); @@ -83,20 +85,21 @@ const getAllEnvironmentsByTestCase = async (req, res) => { } }; const getAllEnvironmentNamesByTestCase = async (req, res) => { - /* #swagger.tags = ["Environment"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Environment"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const testCaseId = req.params.testCaseId; + const { testCaseId } = req.params; const { error } = idValidation.validate({ id: testCaseId }); if (error) throw new Error(error.details[0].message); const enviroments = await Environment.schema(req.database).findAll({ + attributes: ['id', 'name'], where: { testCaseId - }, - attributes: ['id', 'name'] + } }); return res.status(200).json(enviroments); } catch (err) { @@ -105,13 +108,14 @@ const getAllEnvironmentNamesByTestCase = async (req, res) => { }; const createColumnForEnvironment = async (req, res) => { - /* #swagger.tags = ["Environment"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Environment"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const columnName = req.body.name; - const testCaseId = req.params.testCaseId; + const { testCaseId } = req.params; const { error } = nameTestCaseId.validate({ name: columnName, testCaseId @@ -119,10 +123,10 @@ const createColumnForEnvironment = async (req, res) => { if (error) throw new Error(error.details[0].message); const enviroments = await Environment.schema(req.database).findAll({ + attributes: ['id'], where: { testCaseId - }, - attributes: ['id'] + } }); const payload = enviroments.map((el) => { @@ -137,9 +141,10 @@ const createColumnForEnvironment = async (req, res) => { } }; const updateColumnValue = async (req, res) => { - /* #swagger.tags = ["Environment"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Environment"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { value, envId, name } = req.body; @@ -147,7 +152,7 @@ const updateColumnValue = async (req, res) => { const { error } = updateColumnValidation.validate(req.body); if (error) throw new Error(error.details[0].message); - const updateColumnValue = await Column.schema(req.database).update( + const updatedColumnValue = await Column.schema(req.database).update( { value }, { where: { @@ -156,24 +161,24 @@ const updateColumnValue = async (req, res) => { } } ); - if (updateColumnValue[0]) { + if (updatedColumnValue[0]) { return res.status(200).json({ message: 'Column updated successfully!' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (err) { getError(err, res); } }; const deleteColumnFromEnvironment = async (req, res) => { - /* #swagger.tags = ["Environment"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Environment"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const columnName = req.params.name; - const testCaseId = req.params.testCaseId; + const { testCaseId } = req.params; const { error } = nameTestCaseId.validate({ name: columnName, @@ -182,10 +187,10 @@ const deleteColumnFromEnvironment = async (req, res) => { if (error) throw new Error(error.details[0].message); const enviroments = await Environment.schema(req.database).findAll({ + attributes: ['id'], where: { testCaseId - }, - attributes: ['id'] + } }); const payload = enviroments.map((el) => { @@ -194,27 +199,27 @@ const deleteColumnFromEnvironment = async (req, res) => { }); const deletedColumn = await Column.schema(req.database).destroy({ where: { - name: columnName, - envId: payload + envId: payload, + name: columnName } }); if (deletedColumn > 0) { return res.status(200).json({ message: 'Column Deleted!' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (err) { getError(err, res); } }; const deleteEnvironment = async (req, res) => { - /* #swagger.tags = ["Environment"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Environment"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const envId = req.params.envId; + const { envId } = req.params; const { error } = idValidation.validate({ id: envId }); if (error) throw new Error(error.details[0].message); await Column.schema(req.database).destroy({ @@ -230,12 +235,11 @@ const deleteEnvironment = async (req, res) => { if (deletedEnv > 0) { return res.status(200).json({ message: 'Environment Deleted!' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (err) { getError(err, res); } }; -export { createEnvironment, getAllEnvironmentsByTestCase, createColumnForEnvironment, deleteColumnFromEnvironment, updateColumnValue, getAllEnvironmentNamesByTestCase, deleteEnvironment }; +export { createColumnForEnvironment, createEnvironment, deleteColumnFromEnvironment, deleteEnvironment, getAllEnvironmentNamesByTestCase, getAllEnvironmentsByTestCase, updateColumnValue }; diff --git a/TestCase/Controllers/executionHistory.js b/TestCase/Controllers/executionHistory.js index 1bada37..1cab56f 100644 --- a/TestCase/Controllers/executionHistory.js +++ b/TestCase/Controllers/executionHistory.js @@ -1,28 +1,30 @@ -import db from '#utils/dataBaseConnection.js'; -import getError from '#utils/error.js'; import moment from 'moment'; + +import errorContstants from '#constants/error.js'; import { deleteS3Folder } from '#storage/Service/awsService.js'; +import db from '#utils/dataBaseConnection.js'; +import getError from '#utils/error.js'; import { idValidation } from '#validations/index.js'; -import errorContstants from '#constants/error.js'; const ExecutionHistory = db.executionHistory; const ProcessHistory = db.processHistory; const TestStepHistory = db.testStepHistory; const getAllExecutionHistoryByTestCase = async (req, res) => { - /* #swagger.tags = ["Execution History"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Execution History"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const testCaseId = req.params.testCaseId; + const { testCaseId } = req.params; const { error } = idValidation.validate({ id: testCaseId }); if (error) throw new Error(error.details[0].message); const executionHistories = await ExecutionHistory.schema(req.database).findAll({ + order: [['createdAt', 'DESC']], where: { testCaseId - }, - order: [['createdAt', 'DESC']] + } }); return res.status(200).json(executionHistories); @@ -32,12 +34,13 @@ const getAllExecutionHistoryByTestCase = async (req, res) => { }; const deleteExecutionHistoryById = async (req, res) => { - /* #swagger.tags = ["Execution History"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Execution History"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const executionHistoryId = req.params.executionHistoryId; + const { executionHistoryId } = req.params; const { error } = idValidation.validate({ id: executionHistoryId }); if (error) throw new Error(error.details[0].message); const deletedExecutionHistory = await ExecutionHistory.schema(req.database).destroy({ @@ -47,19 +50,19 @@ const deleteExecutionHistoryById = async (req, res) => { if (deletedExecutionHistory > 0) { deleteS3Folder(req.database.split('_')[1], req.params.executionHistoryId); return res.status(200).json({ message: 'Execution History deleted successfully' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (err) { getError(err, res); } }; const deleteExecutionHistoryByTestCase = async (req, res) => { - /* #swagger.tags = ["Execution History"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Execution History"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const testCaseId = req.params.testCaseId; + const { testCaseId } = req.params; const allHsitory = await ExecutionHistory.schema(req.database).findAll({ where: { testCaseId } @@ -75,35 +78,35 @@ const deleteExecutionHistoryByTestCase = async (req, res) => { }); return res.status(200).json({ message: 'All Execution History deleted successfully' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (err) { getError(err, res); } }; const getExecutionHistoryById = async (req, res) => { - /* #swagger.tags = ["Execution History"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Execution History"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const executionHistoryId = req.params.executionHistoryId; + const { executionHistoryId } = req.params; const { error } = idValidation.validate({ id: executionHistoryId }); if (error) throw new Error(error.details[0].message); const executionHistory = await ExecutionHistory.schema(req.database).findByPk(executionHistoryId, { include: [ { - model: ProcessHistory.schema(req.database), as: 'process', - where: { executionHistoryId }, include: [ { - model: TestStepHistory.schema(req.database), as: 'testSteps', + model: TestStepHistory.schema(req.database), where: { executionHistoryId } } - ] + ], + model: ProcessHistory.schema(req.database), + where: { executionHistoryId } } ] }); @@ -120,4 +123,4 @@ const getExecutionHistoryById = async (req, res) => { } }; -export { getAllExecutionHistoryByTestCase, deleteExecutionHistoryById, getExecutionHistoryById, deleteExecutionHistoryByTestCase }; +export { deleteExecutionHistoryById, deleteExecutionHistoryByTestCase, getAllExecutionHistoryByTestCase, getExecutionHistoryById }; diff --git a/TestCase/Controllers/executionSuiteController.js b/TestCase/Controllers/executionSuiteController.js index 7a6d978..92ecc48 100644 --- a/TestCase/Controllers/executionSuiteController.js +++ b/TestCase/Controllers/executionSuiteController.js @@ -1,18 +1,20 @@ +import { Op } from 'sequelize'; + import errorContstants from '#constants/error.js'; import db from '#utils/dataBaseConnection.js'; import getError from '#utils/error.js'; import { idValidation } from '#validations/index.js'; -import { Op } from 'sequelize'; const ExecutionSuite = db.executionSuites; const CaseExecution = db.testCaseExecutionMappings; const TestCase = db.testCases; const Environment = db.enviroments; const addExecutionSuite = async (req, res) => { - /* #swagger.tags = ["Execution Suite"] - #swagger.security = [{"apiKeyAuth": []}] - - */ + /* + * #swagger.tags = ["Execution Suite"] + * #swagger.security = [{"apiKeyAuth": []}] + * + */ try { const executionSuite = await ExecutionSuite.schema(req.database).create({ ...req.body, createdByUser: req.user.id }); return res.status(200).json(executionSuite); @@ -22,15 +24,16 @@ const addExecutionSuite = async (req, res) => { }; const getAllExecutionSuite = async (req, res) => { - /* #swagger.tags = ["Execution Suite"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Execution Suite"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const projectId = req.headers['x-project-id']; const executionSuite = await ExecutionSuite.schema(req.database).findAll({ - where: { projectId }, - attributes: ['id', 'name', 'createdByUser', 'tags', 'description', 'createdAt'] + attributes: ['id', 'name', 'createdByUser', 'tags', 'description', 'createdAt'], + where: { projectId } }); return res.status(200).json(executionSuite); @@ -40,11 +43,12 @@ const getAllExecutionSuite = async (req, res) => { }; const deleteExecutionSuite = async (req, res) => { - /* #swagger.tags = ["Execution Suite"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Execution Suite"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const executionSuiteId = req.params.executionSuiteId; + const { executionSuiteId } = req.params; const { error } = idValidation.validate({ id: executionSuiteId }); if (error) throw new Error(error.details[0].message); @@ -52,16 +56,17 @@ const deleteExecutionSuite = async (req, res) => { where: { id: executionSuiteId } }); if (deletedExecutionSuite > 0) return res.status(200).json({ message: 'Execution Suite deleted successfully!' }); - else return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (error) { getError(error, res); } }; const addTestCaseToExecutionSuite = async (req, res) => { - /* #swagger.tags = ["Execution Suite"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Execution Suite"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { testCaseId, executionSuiteId, step } = req.body; @@ -75,24 +80,24 @@ const addTestCaseToExecutionSuite = async (req, res) => { } }); - const newMapping = await CaseExecution.schema(req.database).create({ testCaseId, executionSuiteId, step }); + const newMapping = await CaseExecution.schema(req.database).create({ executionSuiteId, step, testCaseId }); const addedTestCase = await CaseExecution.schema(req.database).findOne({ - where: { id: newMapping.dataValues.id }, attributes: ['id', 'step', 'createdAt'], include: [ { - model: TestCase.schema(req.database), attributes: ['id', 'name'], include: [ { - model: Environment.schema(req.database), as: 'environments', - attributes: ['id', 'name'] + attributes: ['id', 'name'], + model: Environment.schema(req.database) } - ] + ], + model: TestCase.schema(req.database) } - ] + ], + where: { id: newMapping.dataValues.id } }); return res.status(200).json({ ...addedTestCase.dataValues, message: 'Test Case added!' }); @@ -102,9 +107,10 @@ const addTestCaseToExecutionSuite = async (req, res) => { }; const removeTestCaseFromExecutionSuite = async (req, res) => { - /* #swagger.tags = ["Execution Suite"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Execution Suite"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const caseExecutionId = req.params.id; @@ -127,39 +133,47 @@ const removeTestCaseFromExecutionSuite = async (req, res) => { }; const getTestCaseByExecutionSuiteId = async (req, res) => { - /* #swagger.tags = ["Execution Suite"] - #swagger.security = [{"apiKeyAuth": []}] */ + /* + * #swagger.tags = ["Execution Suite"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const executionSuiteId = req.params.executionSuiteId; - // const { error } = idValidation.validate({ id: userId }); - // if (error) throw new Error(error.details[0].message); + const { executionSuiteId } = req.params; + /* + * Const { error } = idValidation.validate({ id: userId }); + * if (error) throw new Error(error.details[0].message); + */ const testcases = await CaseExecution.schema(req.database).findAll({ - where: { executionSuiteId }, attributes: ['id', 'step', 'createdAt'], include: [ { - model: TestCase.schema(req.database), attributes: ['id', 'name'], include: [ { - model: Environment.schema(req.database), as: 'environments', - attributes: ['id', 'name'] + attributes: ['id', 'name'], + model: Environment.schema(req.database) } - ] + ], + model: TestCase.schema(req.database) } ], order: [ ['step', 'ASC'] - // [TestStep, "step", "ASC"], - // [ReusableProcess, TestStep, "step", "ASC"], - ] + /* + * [TestStep, "step", "ASC"], + * [ReusableProcess, TestStep, "step", "ASC"], + */ + ], + where: { executionSuiteId } }); - // const updatedArray = testcases.map((el) => { - // return { ...el.testCase.dataValues }; - // }); + /* + * Const updatedArray = testcases.map((el) => { + * return { ...el.testCase.dataValues }; + * }); + */ return res.status(200).json(testcases); } catch (error) { @@ -168,20 +182,22 @@ const getTestCaseByExecutionSuiteId = async (req, res) => { }; const getExecutionSuiteDetailsById = async (req, res) => { - /* #swagger.tags = ["Execution Suite"] - #swagger.security = [{"apiKeyAuth": []}] */ + /* + * #swagger.tags = ["Execution Suite"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const executionSuiteId = req.params.executionSuiteId; + const { executionSuiteId } = req.params; const { error } = idValidation.validate({ id: executionSuiteId }); if (error) throw new Error(error.details[0].message); const executionSuite = await ExecutionSuite.schema(req.database).findOne({ + attributes: ['id', 'name', 'createdAt', 'updatedAt', 'description', 'tags', 'createdByUser'], where: { id: executionSuiteId - }, - attributes: ['id', 'name', 'createdAt', 'updatedAt', 'description', 'tags', 'createdByUser'] + } }); const totalTestCase = await CaseExecution.schema(req.database).count({ where: { executionSuiteId } @@ -194,17 +210,20 @@ const getExecutionSuiteDetailsById = async (req, res) => { }; const editExecutionSuite = async (req, res) => { - /* #swagger.tags = ["Execution Suite"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Execution Suite"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const executionSuiteId = req.params.executionSuiteId; + const { executionSuiteId } = req.params; - // const { error } = updateProjectValidation.validate({ - // ...req.body, - // projectId, - // }); - // if (error) throw new Error(error.details[0].message); + /* + * Const { error } = updateProjectValidation.validate({ + * ...req.body, + * projectId, + * }); + * if (error) throw new Error(error.details[0].message); + */ const updatedExecutionSuite = await ExecutionSuite.schema(req.database).update(req.body, { where: { @@ -214,9 +233,8 @@ const editExecutionSuite = async (req, res) => { if (updatedExecutionSuite[0]) { return res.status(200).json({ message: 'Execution Suite Updated Successfully!' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (error) { getError(error, res); } @@ -224,11 +242,11 @@ const editExecutionSuite = async (req, res) => { export { addExecutionSuite, - getAllExecutionSuite, - deleteExecutionSuite, addTestCaseToExecutionSuite, - removeTestCaseFromExecutionSuite, - getTestCaseByExecutionSuiteId, + deleteExecutionSuite, + editExecutionSuite, + getAllExecutionSuite, getExecutionSuiteDetailsById, - editExecutionSuite + getTestCaseByExecutionSuiteId, + removeTestCaseFromExecutionSuite }; diff --git a/TestCase/Controllers/machineController.js b/TestCase/Controllers/machineController.js index b722f6a..60f38fe 100644 --- a/TestCase/Controllers/machineController.js +++ b/TestCase/Controllers/machineController.js @@ -1,13 +1,14 @@ +import errorContstants from '#constants/error.js'; import db from '#utils/dataBaseConnection.js'; import getError from '#utils/error.js'; import { idValidation } from '#validations/index.js'; -import errorContstants from '#constants/error.js'; const Machine = db.machines; export const addMachine = async (req, res) => { - /* #swagger.tags = ["Machine"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Machine"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { if (!req.user.customerAdmin) return res.status(401).json({ error: errorContstants.UNAUTHORIZED }); @@ -25,9 +26,10 @@ export const addMachine = async (req, res) => { }; export const getAllMachine = async (req, res) => { - /* #swagger.tags = ["Machine"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Machine"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const machines = await Machine.schema(req.database).findAll({ attributes: ['id', 'name', 'url', 'createdAt'] @@ -40,12 +42,13 @@ export const getAllMachine = async (req, res) => { }; export const removeMachine = async (req, res) => { - /* #swagger.tags = ["Machine"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Machine"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { if (!req.user.customerAdmin) return res.status(401).json({ error: errorContstants.UNAUTHORIZED }); - const machineId = req.params.machineId; + const { machineId } = req.params; const { error } = idValidation.validate({ id: machineId }); if (error) throw new Error(error.details[0].message); @@ -53,7 +56,7 @@ export const removeMachine = async (req, res) => { where: { id: machineId } }); if (deletedMachine > 0) return res.status(200).json({ message: 'Machine deleted successfully!' }); - else return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (error) { getError(error, res); } diff --git a/TestCase/Controllers/object.js b/TestCase/Controllers/object.js index cb3fc92..6684446 100644 --- a/TestCase/Controllers/object.js +++ b/TestCase/Controllers/object.js @@ -1,17 +1,18 @@ +import errorContstants from '#constants/error.js'; +import { saveObjectLocatorValidation, updateObjectValidation } from '#testcase/Validations/object.js'; import db from '#utils/dataBaseConnection.js'; import getError from '#utils/error.js'; -import { idValidation, nameDesTagPrjValidation, createLogValidation } from '#validations/index.js'; -import { updateObjectValidation, saveObjectLocatorValidation } from '#testcase/Validations/object.js'; -import errorContstants from '#constants/error.js'; +import { createLogValidation, idValidation, nameDesTagPrjValidation } from '#validations/index.js'; const Object = db.objects; const ObjectLocator = db.ObjectLocators; const ObjectLog = db.objectLogs; const saveObject = async (req, res) => { - /* #swagger.tags = ["Test Object"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Object"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { error } = nameDesTagPrjValidation.validate(req.body); @@ -27,26 +28,27 @@ const saveObject = async (req, res) => { } }; const getObjectDetailsById = async (req, res) => { - /* #swagger.tags = ["Test Object"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Object"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const objectId = req.params.objectId; + const { objectId } = req.params; const { error } = idValidation.validate({ id: objectId }); if (error) throw new Error(error.details[0].message); const testCase = await Object.schema(req.database).findOne({ - where: { - id: objectId - }, attributes: ['id', 'name', 'createdAt', 'updatedAt', 'description', 'tags', 'createdByUser'], include: [ { - model: ObjectLocator.schema(req.database), - as: 'locators' + as: 'locators', + model: ObjectLocator.schema(req.database) } - ] + ], + where: { + id: objectId + } }); return res.status(200).json(testCase); @@ -56,12 +58,13 @@ const getObjectDetailsById = async (req, res) => { }; const updateObject = async (req, res) => { - /* #swagger.tags = ["Test Object"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Object"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const objectId = req.params.objectId; + const { objectId } = req.params; const { error } = updateObjectValidation.validate({ ...req.body, objectId @@ -76,21 +79,21 @@ const updateObject = async (req, res) => { if (updatedObject[0]) { return res.status(200).json({ message: 'Object updated successfully!' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (err) { getError(err, res); } }; const deleteObject = async (req, res) => { - /* #swagger.tags = ["Test Object"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Object"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const objectId = req.params.objectId; + const { objectId } = req.params; const { error } = idValidation.validate({ id: objectId }); if (error) throw new Error(error.details[0].message); @@ -101,18 +104,18 @@ const deleteObject = async (req, res) => { if (deletedObject > 0) { return res.status(200).json({ message: 'Object deleted successfully' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (err) { getError(err, res); } }; const getAllObject = async (req, res) => { - /* #swagger.tags = ["Test Object"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Object"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const projectId = req.headers['x-project-id']; @@ -120,11 +123,11 @@ const getAllObject = async (req, res) => { if (error) throw new Error(error.details[0].message); const objects = await Object.schema(req.database).findAll({ + attributes: ['id', 'name', 'createdAt', 'updatedAt', 'tags', 'createdByUser'], + order: [['name', 'ASC']], where: { projectId - }, - attributes: ['id', 'name', 'createdAt', 'updatedAt', 'tags', 'createdByUser'], - order: [['name', 'ASC']] + } }); return res.status(200).json(objects); @@ -133,12 +136,13 @@ const getAllObject = async (req, res) => { } }; const getObjectLocatorsByObjectId = async (req, res) => { - /* #swagger.tags = ["Test Object"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Object"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const objectId = req.params.objectId; + const { objectId } = req.params; const { error } = idValidation.validate({ id: objectId }); if (error) throw new Error(error.details[0].message); @@ -156,9 +160,10 @@ const getObjectLocatorsByObjectId = async (req, res) => { }; const saveObjectLocator = async (req, res) => { - /* #swagger.tags = ["Test Object"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Object"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { error } = saveObjectLocatorValidation.validate(req.body); @@ -175,12 +180,13 @@ const saveObjectLocator = async (req, res) => { }; const deleteObjectLocator = async (req, res) => { - /* #swagger.tags = ["Test Object"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Object"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const locatorId = req.params.locatorId; + const { locatorId } = req.params; const { error } = idValidation.validate({ id: locatorId }); if (error) throw new Error(error.details[0].message); @@ -191,31 +197,31 @@ const deleteObjectLocator = async (req, res) => { if (deletedLocator > 0) { return res.status(200).json({ message: 'ObjectLocator deleted successfully' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (err) { getError(err, res); } }; const getObjectLogsByObjectId = async (req, res) => { - /* #swagger.tags = ["Test Object"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Object"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const objectId = req.params.objectId; + const { objectId } = req.params; const { error } = idValidation.validate({ id: objectId }); if (error) throw new Error(error.details[0].message); const locators = await ObjectLog.schema(req.database).findAll({ + attributes: ['id', 'log', 'createdAt', 'createdByUser'], + order: [['createdAt', 'DESC']], where: { objectId - }, - attributes: ['id', 'log', 'createdAt', 'createdByUser'], - order: [['createdAt', 'DESC']] + } }); return res.status(200).json(locators); @@ -225,9 +231,10 @@ const getObjectLogsByObjectId = async (req, res) => { }; const createObjectLog = async (req, res, id, logs = []) => { - /* #swagger.tags = ["Test Object"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Object"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { if (process.env.SAVE_LOGS !== 'true') { @@ -243,9 +250,7 @@ const createObjectLog = async (req, res, id, logs = []) => { }); if (error) throw new Error(error.details[0].message); - const payload = tempLogs.map((el) => { - return { log: el, objectId, createdByUser: req.user.id }; - }); + const payload = tempLogs.map((el) => ({ createdByUser: req.user.id, log: el, objectId })); await ObjectLog.schema(req.database).bulkCreate(payload); if (logs.length === 0) return res.status(201).json('Log Created'); } catch (err) { @@ -255,14 +260,14 @@ const createObjectLog = async (req, res, id, logs = []) => { }; export { + createObjectLog, + deleteObject, + deleteObjectLocator, getAllObject, getObjectDetailsById, - saveObject, - updateObject, - deleteObject, getObjectLocatorsByObjectId, - saveObjectLocator, - deleteObjectLocator, getObjectLogsByObjectId, - createObjectLog + saveObject, + saveObjectLocator, + updateObject }; diff --git a/TestCase/Controllers/reusableProcessController.js b/TestCase/Controllers/reusableProcessController.js index 91919ba..5df4503 100644 --- a/TestCase/Controllers/reusableProcessController.js +++ b/TestCase/Controllers/reusableProcessController.js @@ -1,9 +1,10 @@ -import db from '#utils/dataBaseConnection.js'; -import getError from '#utils/error.js'; -import { idValidation, createLogValidation, nameDesTagPrjValidation } from '#utils/Validations/index.js'; -import { updateReusableProcessValidation } from '#testcase/Validations/reusableProcess.js'; import _ from 'lodash'; + import errorContstants from '#constants/error.js'; +import { updateReusableProcessValidation } from '#testcase/Validations/reusableProcess.js'; +import db from '#utils/dataBaseConnection.js'; +import getError from '#utils/error.js'; +import { createLogValidation, idValidation, nameDesTagPrjValidation } from '#utils/Validations/index.js'; const Object = db.objects; const TestParameter = db.testParameters; @@ -12,9 +13,10 @@ const ReusableProcess = db.reusableProcess; const ReusableProcessLog = db.reusableProcessLogs; const Process = db.process; const saveReusableProcess = async (req, res) => { - /* #swagger.tags = ["Reusable Process"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Reusable Process"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { error } = nameDesTagPrjValidation.validate(req.body); @@ -35,12 +37,13 @@ const saveReusableProcess = async (req, res) => { }; const updateReusableProcess = async (req, res) => { - /* #swagger.tags = ["Reusable Process"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Reusable Process"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const reusableProcessId = req.params.reusableProcessId; + const { reusableProcessId } = req.params; const { error } = updateReusableProcessValidation.validate({ ...req.body, reusableProcessId @@ -55,18 +58,18 @@ const updateReusableProcess = async (req, res) => { if (updatedReusableProcess[0]) { return res.status(200).json({ message: 'ReusableProcess updated successfully!' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (err) { getError(err, res); } }; const getAllReusableProcess = async (req, res) => { - /* #swagger.tags = ["Reusable Process"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Reusable Process"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const projectId = req.headers['x-project-id']; @@ -74,10 +77,10 @@ const getAllReusableProcess = async (req, res) => { if (error) throw new Error(error.details[0].message); const reusableProcesses = await ReusableProcess.schema(req.database).findAll({ + attributes: ['id', 'name', 'updatedAt', 'createdAt', 'tags', 'createdByUser'], where: { projectId - }, - attributes: ['id', 'name', 'updatedAt', 'createdAt', 'tags', 'createdByUser'] + } }); return res.status(200).json(reusableProcesses); @@ -87,12 +90,13 @@ const getAllReusableProcess = async (req, res) => { }; const deleteReusableProcess = async (req, res) => { - /* #swagger.tags = ["Reusable Process"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Reusable Process"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const reusableProcessId = req.params.reusableProcessId; + const { reusableProcessId } = req.params; const { error } = idValidation.validate({ id: reusableProcessId }); @@ -104,29 +108,29 @@ const deleteReusableProcess = async (req, res) => { if (deletedReusableProcess > 0) { return res.status(200).json({ message: 'ReusableProcess deleted successfully' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (err) { getError(err, res); } }; const getReusableProcessDetailsById = async (req, res) => { - /* #swagger.tags = ["Reusable Process"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Reusable Process"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const reusableProcessId = req.params.reusableProcessId; + const { reusableProcessId } = req.params; const { error } = idValidation.validate({ id: reusableProcessId }); if (error) throw new Error(error.details[0].message); const reusableProcess = await ReusableProcess.schema(req.database).findOne({ + attributes: ['id', 'name', 'createdAt', 'updatedAt', 'description', 'tags', 'createdByUser'], where: { id: reusableProcessId - }, - attributes: ['id', 'name', 'createdAt', 'updatedAt', 'description', 'tags', 'createdByUser'] + } }); const totalSteps = await TestStep.schema(req.database).count({ where: { reusableProcessId } @@ -139,22 +143,23 @@ const getReusableProcessDetailsById = async (req, res) => { }; const getTestStepByReusableProcess = async (req, res) => { - /* #swagger.tags = ["Reusable Process"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Reusable Process"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const reusableProcessId = req.params.reusableProcessId; + const { reusableProcessId } = req.params; const { error } = idValidation.validate({ id: reusableProcessId }); if (error) throw new Error(error.details[0].message); const data = await TestStep.schema(req.database).findAll({ - where: { reusableProcessId }, - include: [{ model: Object.schema(req.database) }, { model: TestParameter.schema(req.database) }], - order: [['step', 'ASC']] + + order: [['step', 'ASC']], + where: { reusableProcessId } }); return res.status(200).json(data); @@ -164,22 +169,23 @@ const getTestStepByReusableProcess = async (req, res) => { }; const getReusableProcessLogsById = async (req, res) => { - /* #swagger.tags = ["Reusable Process"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Reusable Process"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const reusableProcessId = req.params.reusableProcessId; + const { reusableProcessId } = req.params; const { error } = idValidation.validate({ id: reusableProcessId }); if (error) throw new Error(error.details[0].message); const logs = await ReusableProcessLog.schema(req.database).findAll({ + attributes: ['id', 'log', 'createdAt', 'createdByUser'], + order: [['createdAt', 'DESC']], where: { reusableProcessId - }, - attributes: ['id', 'log', 'createdAt', 'createdByUser'], - order: [['createdAt', 'DESC']] + } }); return res.status(200).json(logs); @@ -189,9 +195,10 @@ const getReusableProcessLogsById = async (req, res) => { }; const createReusableProcessLog = async (req, res, id, logs = []) => { - /* #swagger.tags = ["Reusable Process"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Reusable Process"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { if (process.env.SAVE_LOGS !== 'true') { @@ -208,9 +215,7 @@ const createReusableProcessLog = async (req, res, id, logs = []) => { }); if (error) throw new Error(error.details[0].message); - const payload = tempLogs.map((el) => { - return { log: el, reusableProcessId, createdByUser: req.user.id }; - }); + const payload = tempLogs.map((el) => ({ createdByUser: req.user.id, log: el, reusableProcessId })); await ReusableProcessLog.schema(req.database).bulkCreate(payload); if (logs.length === 0) res.status(201).json('Log Created'); } catch (err) { @@ -220,29 +225,30 @@ const createReusableProcessLog = async (req, res, id, logs = []) => { }; const convertToReusableProcess = async (req, res) => { - /* #swagger.tags = ["Reusable Process"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Reusable Process"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { await db.sequelize.transaction(async (transaction) => { - const processId = req.params.processId; + const { processId } = req.params; const projectId = req.headers['x-project-id']; const { error } = idValidation.validate({ id: processId }); if (error) throw new Error(error.details[0].message); - const process = await Process.schema(req.database).findByPk(processId); + const processByPk = await Process.schema(req.database).findByPk(processId); - if (process.dataValues.reusableProcessId) { + if (processByPk.dataValues.reusableProcessId) { return res.status(200).json({ message: 'Already Reuasable Process!' }); } const reusableProcess = await ReusableProcess.schema(req.database).create( { - name: process.dataValues.name, createdByUser: req.user.id, + name: processByPk.dataValues.name, projectId }, { transaction } @@ -253,44 +259,44 @@ const convertToReusableProcess = async (req, res) => { reusableProcessId: reusableProcess.dataValues.id }, { + transaction, where: { - id: process.dataValues.id - }, - transaction + id: processByPk.dataValues.id + } } ); TestStep.schema(req.database).update( { - reusableProcessId: reusableProcess.dataValues.id, - processId: null + processId: null, + reusableProcessId: reusableProcess.dataValues.id }, { - where: { processId }, - transaction + transaction, + where: { processId } } ); if (updatedProcess[0]) { - const process = await Process.schema(req.database).findByPk( + const updatedProcessByPk = await Process.schema(req.database).findByPk( processId, { include: [ { - model: ReusableProcess.schema(req.database), include: [ { - model: TestStep.schema(req.database), - include: [{ model: Object.schema(req.database) }, { model: TestParameter.schema(req.database) }] + include: [{ model: Object.schema(req.database) }, { model: TestParameter.schema(req.database) }], + model: TestStep.schema(req.database) } - ] + ], + model: ReusableProcess.schema(req.database) } ] }, { transaction } ); - const temp = _.cloneDeep(process); + const temp = _.cloneDeep(updatedProcessByPk); if (temp.dataValues.reusableProcess) { temp.dataValues.testSteps = temp.dataValues.reusableProcess.dataValues.testSteps; @@ -299,9 +305,8 @@ const convertToReusableProcess = async (req, res) => { delete temp.dataValues.testSteps; } return res.status(200).json({ ...temp.dataValues, message: 'Converted to Reuasable Process!' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); }); } catch (err) { getError(err, res); @@ -309,13 +314,13 @@ const convertToReusableProcess = async (req, res) => { }; export { - saveReusableProcess, - updateReusableProcess, - getAllReusableProcess, + convertToReusableProcess, + createReusableProcessLog, deleteReusableProcess, + getAllReusableProcess, getReusableProcessDetailsById, - getTestStepByReusableProcess, - createReusableProcessLog, getReusableProcessLogsById, - convertToReusableProcess + getTestStepByReusableProcess, + saveReusableProcess, + updateReusableProcess }; diff --git a/TestCase/Controllers/testCaseController.js b/TestCase/Controllers/testCaseController.js index ff7a9cf..714bbe4 100644 --- a/TestCase/Controllers/testCaseController.js +++ b/TestCase/Controllers/testCaseController.js @@ -1,10 +1,11 @@ -import db from '#utils/dataBaseConnection.js'; -import getError from '#utils/error.js'; -import { idValidation, createLogValidation, nameDesTagPrjValidation } from '#validations/index.js'; -import { updateTestCaseValidation, saveProcesValidation, updateProcessValidation } from '#testcase/Validations/testCase.js'; -import { Op } from 'sequelize'; import _ from 'lodash'; +import { Op } from 'sequelize'; + import errorContstants from '#constants/error.js'; +import { saveProcesValidation, updateProcessValidation, updateTestCaseValidation } from '#testcase/Validations/testCase.js'; +import db from '#utils/dataBaseConnection.js'; +import getError from '#utils/error.js'; +import { createLogValidation, idValidation, nameDesTagPrjValidation } from '#validations/index.js'; const TestCase = db.testCases; const Process = db.process; const Object = db.objects; @@ -13,9 +14,10 @@ const TestStep = db.testSteps; const ReusableProcess = db.reusableProcess; const TestCaseLog = db.testCaseLogs; const saveTestCase = async (req, res) => { - /* #swagger.tags = ["Test Case"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Case"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { error } = nameDesTagPrjValidation.validate(req.body); @@ -33,13 +35,14 @@ const saveTestCase = async (req, res) => { }; const updateTestCase = async (req, res) => { - /* #swagger.tags = ["Test Case"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Case"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - // const { name, tags } = req.body; - const testCaseId = req.params.testCaseId; + // Const { name, tags } = req.body; + const { testCaseId } = req.params; const { error } = updateTestCaseValidation.validate({ ...req.body, testCaseId @@ -54,18 +57,18 @@ const updateTestCase = async (req, res) => { if (updatedTestCase[0]) { return res.status(200).json({ message: 'TestCase updated successfully!' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (err) { getError(err, res); } }; const getAllTestCase = async (req, res) => { - /* #swagger.tags = ["Test Case"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Case"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const projectId = req.headers['x-project-id']; @@ -73,10 +76,10 @@ const getAllTestCase = async (req, res) => { if (error) throw new Error(error.details[0].message); const testCases = await TestCase.schema(req.database).findAll({ + attributes: ['id', 'name', 'updatedAt', 'createdAt', 'tags', 'createdByUser'], where: { projectId - }, - attributes: ['id', 'name', 'updatedAt', 'createdAt', 'tags', 'createdByUser'] + } }); return res.status(200).json(testCases); @@ -86,12 +89,13 @@ const getAllTestCase = async (req, res) => { }; const deleteTestCase = async (req, res) => { - /* #swagger.tags = ["Test Case"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Case"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const testCaseId = req.params.testCaseId; + const { testCaseId } = req.params; const { error } = idValidation.validate({ id: testCaseId }); if (error) throw new Error(error.details[0].message); @@ -101,45 +105,41 @@ const deleteTestCase = async (req, res) => { if (deletedTestCase > 0) { return res.status(200).json({ message: 'TestCase deleted successfully' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (err) { getError(err, res); } }; const getTestCaseDetailsById = async (req, res) => { - /* #swagger.tags = ["Test Case"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Case"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const testCaseId = req.params.testCaseId; + const { testCaseId } = req.params; const { error } = idValidation.validate({ id: testCaseId }); if (error) throw new Error(error.details[0].message); const testCase = await TestCase.schema(req.database).findOne({ + attributes: ['id', 'name', 'createdAt', 'updatedAt', 'description', 'tags', 'createdByUser'], where: { id: testCaseId - }, - attributes: ['id', 'name', 'createdAt', 'updatedAt', 'description', 'tags', 'createdByUser'] + } }); const totalProcess = await Process.schema(req.database).findAll({ where: { testCaseId } }); const processCount = await Process.schema(req.database).count({ - where: { testCaseId, reusableProcessId: null } + where: { reusableProcessId: null, testCaseId } }); const reusableProcessCount = totalProcess.length - processCount; - const allStepId = await totalProcess.map((el) => { - return el.id; - }); - const allReusableProcessId = await totalProcess.map((el) => { - return el.reusableProcessId; - }); + const allStepId = await totalProcess.map((el) => el.id); + const allReusableProcessId = await totalProcess.map((el) => el.reusableProcessId); const stepCount = await TestStep.schema(req.database).count({ where: { [Op.or]: [{ processId: allStepId }, { reusableProcessId: allReusableProcessId }] @@ -148,8 +148,8 @@ const getTestCaseDetailsById = async (req, res) => { return res.status(200).json({ ...testCase.dataValues, reusableProcessCount, - totalProcess: totalProcess.length, - stepCount + stepCount, + totalProcess: totalProcess.length }); } catch (err) { getError(err, res); @@ -157,40 +157,43 @@ const getTestCaseDetailsById = async (req, res) => { }; const getTestStepByTestCase = async (req, res) => { - /* #swagger.tags = ["Test Case"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Case"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - // const { error } = nameValidation.validate(req.body); - // if (error) throw new Error(error.details[0].message); + /* + * Const { error } = nameValidation.validate(req.body); + * if (error) throw new Error(error.details[0].message); + */ - const testCaseId = req.params.testCaseId; + const { testCaseId } = req.params; const { error } = idValidation.validate({ id: testCaseId }); if (error) throw new Error(error.details[0].message); const data = await Process.schema(req.database).findAll({ - where: { testCaseId }, include: [ { - model: TestStep.schema(req.database), - include: [{ model: Object.schema(req.database) }, { model: TestParameter.schema(req.database) }] + include: [{ model: Object.schema(req.database) }, { model: TestParameter.schema(req.database) }], + model: TestStep.schema(req.database) }, { - model: ReusableProcess.schema(req.database), include: [ { - model: TestStep.schema(req.database), - include: [{ model: Object.schema(req.database) }, { model: TestParameter.schema(req.database) }] + include: [{ model: Object.schema(req.database) }, { model: TestParameter.schema(req.database) }], + model: TestStep.schema(req.database) } - ] + ], + model: ReusableProcess.schema(req.database) } ], order: [ ['step', 'ASC'], [TestStep, 'step', 'ASC'], [ReusableProcess, TestStep, 'step', 'ASC'] - ] + ], + where: { testCaseId } }); const updatedTestCase = data.map((process) => { @@ -209,9 +212,10 @@ const getTestStepByTestCase = async (req, res) => { }; const saveProcess = async (req, res) => { - /* #swagger.tags = ["Test Case"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Case"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { error } = saveProcesValidation.validate(req.body); @@ -222,35 +226,35 @@ const saveProcess = async (req, res) => { await Process.schema(req.database).increment('step', { by: 1, where: { - testCaseId: { [Op.eq]: testCaseId }, step: { [Op.gte]: step - } + }, + testCaseId: { [Op.eq]: testCaseId } } }); const data = await Process.schema(req.database).create(req.body, { include: [ { - model: TestStep.schema(req.database), - include: [{ model: TestParameter.schema(req.database) }] + include: [{ model: TestParameter.schema(req.database) }], + model: TestStep.schema(req.database) } ] }); const process = await Process.schema(req.database).findByPk(data.id, { include: [ { - model: TestStep.schema(req.database), - include: [{ model: Object.schema(req.database) }, { model: TestParameter.schema(req.database) }] + include: [{ model: Object.schema(req.database) }, { model: TestParameter.schema(req.database) }], + model: TestStep.schema(req.database) }, { - model: ReusableProcess.schema(req.database), include: [ { - model: TestStep.schema(req.database), - include: [{ model: Object.schema(req.database) }, { model: TestParameter.schema(req.database) }] + include: [{ model: Object.schema(req.database) }, { model: TestParameter.schema(req.database) }], + model: TestStep.schema(req.database) } - ] + ], + model: ReusableProcess.schema(req.database) } ] }); @@ -269,12 +273,13 @@ const saveProcess = async (req, res) => { }; const updateProcess = async (req, res) => { - /* #swagger.tags = ["Test Case"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Case"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const processId = req.params.processId; + const { processId } = req.params; const { error } = updateProcessValidation.validate({ ...req.body, processId @@ -291,13 +296,13 @@ const updateProcess = async (req, res) => { const process = await Process.schema(req.database).findByPk(processId, { include: [ { - model: ReusableProcess.schema(req.database), include: [ { - model: TestStep.schema(req.database), - include: [{ model: Object.schema(req.database) }, { model: TestParameter.schema(req.database) }] + include: [{ model: Object.schema(req.database) }, { model: TestParameter.schema(req.database) }], + model: TestStep.schema(req.database) } - ] + ], + model: ReusableProcess.schema(req.database) } ] }); @@ -311,21 +316,21 @@ const updateProcess = async (req, res) => { delete temp.dataValues.testSteps; } return res.status(200).json({ ...temp.dataValues, message: 'Process Updated' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (err) { getError(err, res); } }; const deleteProcess = async (req, res) => { - /* #swagger.tags = ["Test Case"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Case"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const processId = req.params.processId; + const { processId } = req.params; const { error } = idValidation.validate({ id: processId }); if (error) throw new Error(error.details[0].message); @@ -340,39 +345,39 @@ const deleteProcess = async (req, res) => { await Process.schema(req.database).decrement('step', { by: 1, where: { - testCaseId: { [Op.eq]: deletingProcess.testCaseId }, step: { [Op.gt]: deletingProcess.step - } + }, + testCaseId: { [Op.eq]: deletingProcess.testCaseId } } }); return res.status(200).json({ message: 'Process deleted successfully' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (err) { getError(err, res); } }; const getTestCaseLogsById = async (req, res) => { - /* #swagger.tags = ["Test Case"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Case"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const testCaseId = req.params.testCaseId; + const { testCaseId } = req.params; const { error } = idValidation.validate({ id: testCaseId }); if (error) throw new Error(error.details[0].message); const locators = await TestCaseLog.schema(req.database).findAll({ + attributes: ['id', 'log', 'createdAt', 'createdByUser'], + order: [['createdAt', 'DESC']], where: { testCaseId - }, - attributes: ['id', 'log', 'createdAt', 'createdByUser'], - order: [['createdAt', 'DESC']] + } }); return res.status(200).json(locators); @@ -382,9 +387,10 @@ const getTestCaseLogsById = async (req, res) => { }; const createTestCaseLog = async (req, res, id, logs = []) => { - /* #swagger.tags = ["Test Case"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Case"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { if (process.env.SAVE_LOGS !== 'true') { @@ -400,9 +406,7 @@ const createTestCaseLog = async (req, res, id, logs = []) => { logs: tempLogs }); if (error) throw new Error(error.details[0].message); - const payload = tempLogs.map((el) => { - return { log: el, testCaseId, createdByUser: req.user.id }; - }); + const payload = tempLogs.map((el) => ({ createdByUser: req.user.id, log: el, testCaseId })); await TestCaseLog.schema(req.database).bulkCreate(payload); if (logs.length === 0) return res.status(201).json('Log Created'); } catch (err) { @@ -412,15 +416,15 @@ const createTestCaseLog = async (req, res, id, logs = []) => { }; export { - saveTestCase, - updateTestCase, - getAllTestCase, + createTestCaseLog, + deleteProcess, deleteTestCase, + getAllTestCase, getTestCaseDetailsById, + getTestCaseLogsById, getTestStepByTestCase, saveProcess, + saveTestCase, updateProcess, - deleteProcess, - getTestCaseLogsById, - createTestCaseLog + updateTestCase }; diff --git a/TestCase/Controllers/testStepController.js b/TestCase/Controllers/testStepController.js index 5d2a8c1..8ab0fb1 100644 --- a/TestCase/Controllers/testStepController.js +++ b/TestCase/Controllers/testStepController.js @@ -1,17 +1,19 @@ +import { Op } from 'sequelize'; + +import errorContstants from '#constants/error.js'; +import { saveTestStepValidation, updateTestStepValidation } from '#testcase/Validations/testStep.js'; import db from '#utils/dataBaseConnection.js'; import getError from '#utils/error.js'; -import { saveTestStepValidation, updateTestStepValidation } from '#testcase/Validations/testStep.js'; import { idValidation } from '#validations/index.js'; -import { Op } from 'sequelize'; -import errorContstants from '#constants/error.js'; const TestStep = db.testSteps; const Object = db.objects; const TestParameter = db.testParameters; const saveTestStep = async (req, res) => { - /* #swagger.tags = ["Test Step"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Step"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { await db.sequelize.transaction(async (transaction) => { @@ -20,9 +22,7 @@ const saveTestStep = async (req, res) => { const permissionName = reusableProcessId ? 'Reusable Process' : 'Test Case'; if (!req.user.customerAdmin) { - const allowed = await req.user.permissions.some((permission) => { - return permissionName === permission.name && permission.edit; - }); + const allowed = await req.user.permissions.some((permission) => permissionName === permission.name && permission.edit); if (!allowed) return res.status(401).json({ error: errorContstants.UNAUTHORIZED }); } @@ -32,34 +32,30 @@ const saveTestStep = async (req, res) => { if (processId) { await TestStep.schema(req.database).increment('step', { by: 1, + transaction, where: { processId: { [Op.eq]: processId }, step: { [Op.gte]: step } - }, - transaction + } }); } else { await TestStep.schema(req.database).increment('step', { by: 1, + transaction, where: { reusableProcessId: { [Op.eq]: reusableProcessId }, step: { [Op.gte]: step } - }, - transaction + } }); } const teststep = await TestStep.schema(req.database).create(req.body, { transaction }); const parameterPayload = req.body.parameters - .filter((el) => { - return el.property; - }) - .map((el) => { - return { ...el, testStepId: teststep.id }; - }); + .filter((el) => el.property) + .map((el) => ({ ...el, testStepId: teststep.id })); await TestParameter.schema(req.database).bulkCreate(parameterPayload, { transaction }); const stepData = await TestStep.schema(req.database).findByPk(teststep.id, { include: [{ model: Object.schema(req.database) }, { model: TestParameter.schema(req.database) }], @@ -73,22 +69,21 @@ const saveTestStep = async (req, res) => { }; const updateTestStep = async (req, res) => { - /* #swagger.tags = ["Test Step"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Step"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { await db.sequelize.transaction(async (transaction) => { - const testStepId = req.params.testStepId; + const { testStepId } = req.params; const updatingStep = await TestStep.schema(req.database).findByPk(testStepId); const permissionName = updatingStep.reusableProcessId ? 'Reusable Process' : 'Test Case'; if (!req.user.customerAdmin) { - const allowed = await req.user.permissions.some((permission) => { - return permissionName === permission.name && permission.edit; - }); + const allowed = await req.user.permissions.some((permission) => permissionName === permission.name && permission.edit); if (!allowed) return res.status(401).json({ error: errorContstants.UNAUTHORIZED }); } @@ -101,25 +96,21 @@ const updateTestStep = async (req, res) => { const updatedTestStep = await TestStep.schema(req.database).update( { ...req.body, objectId: req.body.objectId || null }, { + transaction, where: { id: testStepId - }, - transaction + } } ); await TestParameter.schema(req.database).destroy({ - where: { testStepId }, - transaction + transaction, + where: { testStepId } }); const parameterPayload = req.body.parameters - .filter((el) => { - return el.property; - }) - .map((el) => { - return { ...el, testStepId }; - }); + .filter((el) => el.property) + .map((el) => ({ ...el, testStepId })); await TestParameter.schema(req.database).bulkCreate(parameterPayload, { transaction }); @@ -133,9 +124,8 @@ const updateTestStep = async (req, res) => { ...step.dataValues, message: 'TestStep updated successfully!' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); }); } catch (err) { getError(err, res); @@ -143,22 +133,21 @@ const updateTestStep = async (req, res) => { }; const deleteTestStep = async (req, res) => { - /* #swagger.tags = ["Test Step"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Test Step"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { await db.sequelize.transaction(async (transaction) => { - const testStepId = req.params.testStepId; + const { testStepId } = req.params; const deletingTestStep = await TestStep.schema(req.database).findByPk(testStepId); const permissionName = deletingTestStep.reusableProcessId ? 'Reusable Process' : 'Test Case'; if (!req.user.customerAdmin) { - const allowed = await req.user.permissions.some((permission) => { - return permissionName === permission.name && permission.edit; - }); + const allowed = await req.user.permissions.some((permission) => permissionName === permission.name && permission.edit); if (!allowed) return res.status(401).json({ error: errorContstants.UNAUTHORIZED }); } @@ -166,42 +155,41 @@ const deleteTestStep = async (req, res) => { if (error) throw new Error(error.details[0].message); const deletedTestStep = await TestStep.schema(req.database).destroy({ - where: { id: testStepId }, - transaction + transaction, + where: { id: testStepId } }); if (deletedTestStep > 0) { if (deletingTestStep.processId) { await TestStep.schema(req.database).decrement('step', { by: 1, + transaction, where: { processId: { [Op.eq]: deletingTestStep.processId }, step: { [Op.gt]: deletingTestStep.step } - }, - transaction + } }); } else { await TestStep.schema(req.database).decrement('step', { by: 1, + transaction, where: { reusableProcessId: { [Op.eq]: deletingTestStep.reusableProcessId }, step: { [Op.gt]: deletingTestStep.step } - }, - transaction + } }); } return res.status(200).json({ message: 'TestStep deleted successfully' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); }); } catch (err) { getError(err, res); } }; -export { saveTestStep, updateTestStep, deleteTestStep }; +export { deleteTestStep, saveTestStep, updateTestStep }; diff --git a/TestCase/Models/Environment/Column.js b/TestCase/Models/Environment/Column.js index e5cb1d7..0724b77 100644 --- a/TestCase/Models/Environment/Column.js +++ b/TestCase/Models/Environment/Column.js @@ -1,27 +1,27 @@ export default (sequelize, DataTypes) => { const Column = sequelize.define('columns', { - name: { - type: DataTypes.STRING, + envId: { allowNull: false, + onDelete: 'CASCADE', + references: { + key: 'id', + model: 'environments' + }, + type: DataTypes.INTEGER, validate: { notNull: true } }, - value: { - type: DataTypes.STRING, - allowNull: true - }, - envId: { - type: DataTypes.INTEGER, + name: { allowNull: false, + type: DataTypes.STRING, validate: { notNull: true - }, - references: { - model: 'environments', - key: 'id' - }, - onDelete: 'CASCADE' + } + }, + value: { + allowNull: true, + type: DataTypes.STRING } }); diff --git a/TestCase/Models/Environment/Environment.js b/TestCase/Models/Environment/Environment.js index 928939d..a516645 100644 --- a/TestCase/Models/Environment/Environment.js +++ b/TestCase/Models/Environment/Environment.js @@ -1,23 +1,23 @@ export default (sequelize, DataTypes) => { const Environment = sequelize.define('environments', { name: { - type: DataTypes.STRING, allowNull: false, + type: DataTypes.STRING, validate: { notNull: true } }, testCaseId: { - type: DataTypes.INTEGER, allowNull: false, - validate: { - notNull: true - }, + onDelete: 'CASCADE', references: { - model: 'testCases', - key: 'id' + key: 'id', + model: 'testCases' }, - onDelete: 'CASCADE' + type: DataTypes.INTEGER, + validate: { + notNull: true + } } }); diff --git a/TestCase/Models/ExecutionHistory/ExecutionHistory.js b/TestCase/Models/ExecutionHistory/ExecutionHistory.js index 75cfd16..d498a93 100644 --- a/TestCase/Models/ExecutionHistory/ExecutionHistory.js +++ b/TestCase/Models/ExecutionHistory/ExecutionHistory.js @@ -1,66 +1,66 @@ export default (sequelize, DataTypes) => { const ExecutionHistory = sequelize.define('executionHistories', { - name: { - type: DataTypes.STRING, - allowNull: false, - validate: { - notNull: true - } + continueOnError: { + defaultValue: 0, + type: DataTypes.BOOLEAN, + values: [0, 1] }, description: { - type: DataTypes.STRING, - allowNull: true - }, - testCaseId: { - type: DataTypes.INTEGER, - allowNull: false, - validate: { - notNull: true - }, - references: { - model: 'testCases', - key: 'id' - }, - onDelete: 'CASCADE' - }, - totalSteps: { - type: DataTypes.INTEGER, - defaultValue: 0 + allowNull: true, + type: DataTypes.STRING }, executedByUser: { - type: DataTypes.INTEGER, allowNull: false, + type: DataTypes.INTEGER, validate: { notNull: true } }, finishedAt: { - type: DataTypes.DATE, - allowNull: true + allowNull: true, + type: DataTypes.DATE }, - result: { + headless: { + defaultValue: 0, type: DataTypes.BOOLEAN, values: [0, 1] }, - status: { + name: { + allowNull: false, type: DataTypes.STRING, - values: ['EXECUTING', 'COMPLETE', 'INCOMPLETE'], - defaultValue: 'EXECUTING' + validate: { + notNull: true + } }, - continueOnError: { - type: DataTypes.BOOLEAN, + recordAllSteps: { defaultValue: 0, + type: DataTypes.BOOLEAN, values: [0, 1] }, - headless: { + result: { type: DataTypes.BOOLEAN, - defaultValue: 0, values: [0, 1] }, - recordAllSteps: { - type: DataTypes.BOOLEAN, + status: { + defaultValue: 'EXECUTING', + type: DataTypes.STRING, + values: ['EXECUTING', 'COMPLETE', 'INCOMPLETE'] + }, + testCaseId: { + allowNull: false, + onDelete: 'CASCADE', + references: { + key: 'id', + model: 'testCases' + }, + type: DataTypes.INTEGER, + validate: { + notNull: true + } + }, + totalSteps: { defaultValue: 0, - values: [0, 1] + type: DataTypes.INTEGER } }); diff --git a/TestCase/Models/ExecutionHistory/ProcessHistory.js b/TestCase/Models/ExecutionHistory/ProcessHistory.js index 6ce8757..ad0f3bf 100644 --- a/TestCase/Models/ExecutionHistory/ProcessHistory.js +++ b/TestCase/Models/ExecutionHistory/ProcessHistory.js @@ -1,50 +1,51 @@ export default (sequelize, DataTypes) => { const ProcessHistory = sequelize.define('processHistories', { - processId: { - type: DataTypes.INTEGER, - // unique: true, + comment: { + allowNull: true, + type: DataTypes.STRING + }, + executionHistoryId: { allowNull: false, + onDelete: 'CASCADE', + references: { + key: 'id', + model: 'executionHistories' + }, + type: DataTypes.INTEGER, validate: { notNull: true } }, name: { - type: DataTypes.STRING, allowNull: false, + type: DataTypes.STRING, validate: { notNull: true } }, - comment: { - type: DataTypes.STRING, - allowNull: true - }, - step: { - type: DataTypes.INTEGER, + processId: { + // Unique: true, allowNull: false, + + type: DataTypes.INTEGER, validate: { notNull: true } }, + result: { + type: DataTypes.BOOLEAN, + values: [0, 1] + }, reusableProcess: { - type: DataTypes.JSON, - defaultValue: null + defaultValue: null, + type: DataTypes.JSON }, - executionHistoryId: { - type: DataTypes.INTEGER, + step: { allowNull: false, + type: DataTypes.INTEGER, validate: { notNull: true - }, - references: { - model: 'executionHistories', - key: 'id' - }, - onDelete: 'CASCADE' - }, - result: { - type: DataTypes.BOOLEAN, - values: [0, 1] + } } }); diff --git a/TestCase/Models/ExecutionHistory/TestStepHistory.js b/TestCase/Models/ExecutionHistory/TestStepHistory.js index afe3620..13d7e0f 100644 --- a/TestCase/Models/ExecutionHistory/TestStepHistory.js +++ b/TestCase/Models/ExecutionHistory/TestStepHistory.js @@ -1,69 +1,69 @@ export default (sequelize, DataTypes) => { const TestStepHistory = sequelize.define('testStepHistories', { - testStepId: { - type: DataTypes.INTEGER, + actionEvent: { allowNull: false, + type: DataTypes.STRING, validate: { notNull: true } }, - actionEvent: { - type: DataTypes.STRING, + comment: { + allowNull: true, + type: DataTypes.STRING + }, + executionHistoryId: { allowNull: false, + onDelete: 'CASCADE', + references: { + key: 'id', + model: 'executionHistories' + }, + type: DataTypes.INTEGER, validate: { notNull: true } }, - comment: { - type: DataTypes.STRING, - allowNull: true + failedLog: { + allowNull: true, + type: DataTypes.TEXT }, - step: { - type: DataTypes.INTEGER, + object: { + allowNull: true, + type: DataTypes.JSON + }, + processId: { allowNull: false, + type: DataTypes.INTEGER, validate: { notNull: true } }, - object: { - type: DataTypes.JSON, - allowNull: true - }, - testParameters: { - type: DataTypes.JSON, - allowNull: true + result: { + type: DataTypes.BOOLEAN, + values: [0, 1] }, screenshot: { - type: DataTypes.BOOLEAN, defaultValue: 0, + type: DataTypes.BOOLEAN, values: [0, 1] }, - processId: { - type: DataTypes.INTEGER, + step: { allowNull: false, + type: DataTypes.INTEGER, validate: { notNull: true } }, - executionHistoryId: { - type: DataTypes.INTEGER, + testParameters: { + allowNull: true, + type: DataTypes.JSON + }, + testStepId: { allowNull: false, + type: DataTypes.INTEGER, validate: { notNull: true - }, - references: { - model: 'executionHistories', - key: 'id' - }, - onDelete: 'CASCADE' - }, - result: { - type: DataTypes.BOOLEAN, - values: [0, 1] - }, - failedLog: { - type: DataTypes.TEXT, - allowNull: true + } } }); return TestStepHistory; diff --git a/TestCase/Models/Machine.js b/TestCase/Models/Machine.js index 1299c69..95225de 100644 --- a/TestCase/Models/Machine.js +++ b/TestCase/Models/Machine.js @@ -1,16 +1,16 @@ export default (sequelize, DataTypes) => { const Machine = sequelize.define('machines', { name: { - type: DataTypes.STRING, allowNull: false, + type: DataTypes.STRING, unique: 'name', validate: { notNull: true } }, url: { - type: DataTypes.STRING, allowNull: false, + type: DataTypes.STRING, unique: 'url', validate: { notNull: true @@ -19,146 +19,146 @@ export default (sequelize, DataTypes) => { }); sequelize.models.users.hasMany(sequelize.models.userRoles, { - foreignKey: 'userId', - constraints: false + constraints: false, + foreignKey: 'userId' }); sequelize.models.roles.hasMany(sequelize.models.permissions, { - foreignKey: 'roleId', - constraints: false + constraints: false, + foreignKey: 'roleId' }); sequelize.models.userRoles.hasMany(sequelize.models.permissions, { - foreignKey: 'roleId', - constraints: false + constraints: false, + foreignKey: 'roleId' }); sequelize.models.userRoles.hasOne(sequelize.models.roles, { + constraints: false, foreignKey: 'id', - sourceKey: 'roleId', - constraints: false + sourceKey: 'roleId' }); sequelize.models.projects.hasMany(sequelize.models.testCases, { - sourceKey: 'id', + constraints: false, foreignKey: 'projectId', - constraints: false + sourceKey: 'id' }); sequelize.models.objects.hasMany(sequelize.models.objectLocators, { - foreignKey: 'objectId', as: 'locators', - constraints: false + constraints: false, + foreignKey: 'objectId' }); sequelize.models.projects.hasMany(sequelize.models.userProjects, { - foreignKey: 'projectId', as: 'members', - constraints: false + constraints: false, + foreignKey: 'projectId' }); sequelize.models.userProjects.hasOne(sequelize.models.projects, { + constraints: false, foreignKey: 'id', - sourceKey: 'projectId', - constraints: false + sourceKey: 'projectId' }); sequelize.models.userProjects.hasOne(sequelize.models.users, { + constraints: false, foreignKey: 'id', - sourceKey: 'userId', - constraints: false + sourceKey: 'userId' }); sequelize.models.testCases.hasMany(sequelize.models.processes, { - sourceKey: 'id', + constraints: false, foreignKey: 'testCaseId', - constraints: false + sourceKey: 'id' }); sequelize.models.reusableProcesses.hasMany(sequelize.models.testSteps, { - sourceKey: 'id', + constraints: false, foreignKey: 'reusableProcessId', - constraints: false + sourceKey: 'id' }); sequelize.models.processes.hasMany(sequelize.models.testSteps, { - sourceKey: 'id', + constraints: false, foreignKey: 'processId', - constraints: false + sourceKey: 'id' }); sequelize.models.processes.hasOne(sequelize.models.reusableProcesses, { - sourceKey: 'reusableProcessId', + constraints: false, foreignKey: 'id', - constraints: false + sourceKey: 'reusableProcessId' }); sequelize.models.testSteps.hasMany(sequelize.models.testParameters, { - sourceKey: 'id', + constraints: false, foreignKey: 'testStepId', - constraints: false + sourceKey: 'id' }); sequelize.models.testSteps.hasOne(sequelize.models.objects, { - sourceKey: 'objectId', + constraints: false, foreignKey: 'id', - constraints: false + sourceKey: 'objectId' }); sequelize.models.executionHistories.hasMany(sequelize.models.processHistories, { as: 'process', - sourceKey: 'id', + constraints: false, foreignKey: 'executionHistoryId', - constraints: false + sourceKey: 'id' }); sequelize.models.processHistories.hasMany(sequelize.models.testStepHistories, { as: 'testSteps', - sourceKey: 'processId', + constraints: false, foreignKey: 'processId', - constraints: false + sourceKey: 'processId' }); sequelize.models.environments.hasMany(sequelize.models.columns, { - sourceKey: 'id', + constraints: false, foreignKey: 'envId', - constraints: false + sourceKey: 'id' }); sequelize.models.testCases.hasMany(sequelize.models.environments, { - sourceKey: 'id', + constraints: false, foreignKey: 'testCaseId', - constraints: false + sourceKey: 'id' }); sequelize.models.projects.hasMany(sequelize.models.executionSuites, { - sourceKey: 'id', + constraints: false, foreignKey: 'projectId', - constraints: false + sourceKey: 'id' }); sequelize.models.executionSuites.hasMany(sequelize.models.testCaseExecutionMappings, { - sourceKey: 'id', + constraints: false, foreignKey: 'executionSuiteId', - constraints: false + sourceKey: 'id' }); sequelize.models.testCaseExecutionMappings.hasOne(sequelize.models.testCases, { - sourceKey: 'testCaseId', + constraints: false, foreignKey: 'id', - constraints: false + sourceKey: 'testCaseId' }); sequelize.models.projects.hasMany(sequelize.models.jobManagers, { - sourceKey: 'id', + constraints: false, foreignKey: 'projectId', - constraints: false + sourceKey: 'id' }); sequelize.models.jobManagers.hasMany(sequelize.models.jobs, { - sourceKey: 'id', + constraints: false, foreignKey: 'jobManagerId', - constraints: false + sourceKey: 'id' }); sequelize.models.customers.hasOne(sequelize.models.unverifieds, { - sourceKey: 'email', + constraints: false, foreignKey: 'email', - constraints: false + sourceKey: 'email' }); return Machine; diff --git a/TestCase/Models/Object/Object.js b/TestCase/Models/Object/Object.js index 84c6299..42bcc20 100644 --- a/TestCase/Models/Object/Object.js +++ b/TestCase/Models/Object/Object.js @@ -1,8 +1,12 @@ export default (sequelize, DataTypes) => { const Object = sequelize.define('objects', { - name: { - type: DataTypes.STRING, + createdByUser: { allowNull: false, + references: { + key: 'id', + model: 'users' + }, + type: DataTypes.INTEGER, validate: { notNull: true } @@ -10,32 +14,28 @@ export default (sequelize, DataTypes) => { description: { type: DataTypes.STRING }, - projectId: { - type: DataTypes.INTEGER, + name: { allowNull: false, + type: DataTypes.STRING, validate: { notNull: true - }, + } + }, + projectId: { + allowNull: false, + onDelete: 'CASCADE', references: { - model: 'projects', - key: 'id' + key: 'id', + model: 'projects' }, - onDelete: 'CASCADE' - }, - tags: { - type: DataTypes.JSON, - defaultValue: null - }, - createdByUser: { type: DataTypes.INTEGER, - allowNull: false, validate: { notNull: true - }, - references: { - model: 'users', - key: 'id' } + }, + tags: { + defaultValue: null, + type: DataTypes.JSON } }); diff --git a/TestCase/Models/Object/ObjectLocator.js b/TestCase/Models/Object/ObjectLocator.js index ccb0cd4..dfc3e85 100644 --- a/TestCase/Models/Object/ObjectLocator.js +++ b/TestCase/Models/Object/ObjectLocator.js @@ -1,31 +1,31 @@ export default (sequelize, DataTypes) => { const ObjectLocator = sequelize.define('objectLocators', { - type: { - type: DataTypes.STRING, + locator: { allowNull: false, + type: DataTypes.STRING, validate: { notNull: true } }, - locator: { - type: DataTypes.STRING, + objectId: { allowNull: false, + onDelete: 'CASCADE', + references: { + key: 'id', + model: 'objects' + }, + type: DataTypes.INTEGER, validate: { notNull: true } }, - objectId: { - type: DataTypes.INTEGER, + type: { allowNull: false, + type: DataTypes.STRING, validate: { notNull: true - }, - references: { - model: 'objects', - key: 'id' - }, - onDelete: 'CASCADE' + } } }); diff --git a/TestCase/Models/Object/ObjectLog.js b/TestCase/Models/Object/ObjectLog.js index 75c7818..20aa86e 100644 --- a/TestCase/Models/Object/ObjectLog.js +++ b/TestCase/Models/Object/ObjectLog.js @@ -1,33 +1,33 @@ export default (sequelize, DataTypes) => { const ObjectLogs = sequelize.define('objectLogs', { - log: { - type: DataTypes.STRING, + createdByUser: { allowNull: false, + references: { + key: 'id', + model: 'users' + }, + type: DataTypes.INTEGER, validate: { notNull: true } }, - objectId: { - type: DataTypes.INTEGER, + log: { allowNull: false, + type: DataTypes.STRING, validate: { notNull: true - }, + } + }, + objectId: { + allowNull: false, + onDelete: 'CASCADE', references: { - model: 'objects', - key: 'id' + key: 'id', + model: 'objects' }, - onDelete: 'CASCADE' - }, - createdByUser: { type: DataTypes.INTEGER, - allowNull: false, validate: { notNull: true - }, - references: { - model: 'users', - key: 'id' } } }); diff --git a/TestCase/Models/Process.js b/TestCase/Models/Process.js index 69bce87..432ccfe 100644 --- a/TestCase/Models/Process.js +++ b/TestCase/Models/Process.js @@ -1,47 +1,47 @@ export default (sequelize, DataTypes) => { const Process = sequelize.define('processes', { + comment: { + allowNull: true, + type: DataTypes.STRING + }, + enable: { + defaultValue: 1, + type: DataTypes.BOOLEAN, + values: [0, 1] + }, name: { - type: DataTypes.STRING, allowNull: false, + type: DataTypes.STRING, validate: { notNull: true } }, - comment: { - type: DataTypes.STRING, - allowNull: true + reusableProcessId: { + references: { + key: 'id', + model: 'reusableProcesses' + }, + type: DataTypes.INTEGER + // OnDelete: "CASCADE", }, step: { - type: DataTypes.INTEGER, allowNull: false, + type: DataTypes.INTEGER, validate: { notNull: true } }, - enable: { - type: DataTypes.BOOLEAN, - defaultValue: 1, - values: [0, 1] - }, testCaseId: { - type: DataTypes.INTEGER, allowNull: false, - validate: { - notNull: true - }, + onDelete: 'CASCADE', references: { - model: 'testCases', - key: 'id' + key: 'id', + model: 'testCases' }, - onDelete: 'CASCADE' - }, - reusableProcessId: { type: DataTypes.INTEGER, - references: { - model: 'reusableProcesses', - key: 'id' + validate: { + notNull: true } - // onDelete: "CASCADE", } }); diff --git a/TestCase/Models/ReusableProcess.js b/TestCase/Models/ReusableProcess.js index a1d77ed..288abae 100644 --- a/TestCase/Models/ReusableProcess.js +++ b/TestCase/Models/ReusableProcess.js @@ -1,42 +1,42 @@ export default (sequelize, DataTypes) => { const ReusableProcess = sequelize.define('reusableProcesses', { - name: { - type: DataTypes.STRING, + createdByUser: { allowNull: false, + references: { + key: 'id', + model: 'users' + }, + type: DataTypes.INTEGER, validate: { notNull: true } }, description: { - type: DataTypes.STRING, - allowNull: true + allowNull: true, + type: DataTypes.STRING }, - projectId: { - type: DataTypes.INTEGER, + name: { allowNull: false, + type: DataTypes.STRING, validate: { notNull: true - }, + } + }, + projectId: { + allowNull: false, + onDelete: 'CASCADE', references: { - model: 'projects', - key: 'id' + key: 'id', + model: 'projects' }, - onDelete: 'CASCADE' - }, - tags: { - type: DataTypes.JSON, - defaultValue: null - }, - createdByUser: { type: DataTypes.INTEGER, - allowNull: false, validate: { notNull: true - }, - references: { - model: 'users', - key: 'id' } + }, + tags: { + defaultValue: null, + type: DataTypes.JSON } }); diff --git a/TestCase/Models/ReusableProcessLog.js b/TestCase/Models/ReusableProcessLog.js index 235207f..2eb400b 100644 --- a/TestCase/Models/ReusableProcessLog.js +++ b/TestCase/Models/ReusableProcessLog.js @@ -1,33 +1,33 @@ export default (sequelize, DataTypes) => { const ReusableProcessLogs = sequelize.define('reusableProcessLogs', { - log: { - type: DataTypes.STRING, + createdByUser: { allowNull: false, + references: { + key: 'id', + model: 'users' + }, + type: DataTypes.INTEGER, validate: { notNull: true } }, - reusableProcessId: { - type: DataTypes.INTEGER, + log: { allowNull: false, + type: DataTypes.STRING, validate: { notNull: true - }, + } + }, + reusableProcessId: { + allowNull: false, + onDelete: 'CASCADE', references: { - model: 'reusableProcesses', - key: 'id' + key: 'id', + model: 'reusableProcesses' }, - onDelete: 'CASCADE' - }, - createdByUser: { type: DataTypes.INTEGER, - allowNull: false, validate: { notNull: true - }, - references: { - model: 'users', - key: 'id' } } }); diff --git a/TestCase/Models/TestCase.js b/TestCase/Models/TestCase.js index b5b177c..db593ec 100644 --- a/TestCase/Models/TestCase.js +++ b/TestCase/Models/TestCase.js @@ -1,38 +1,38 @@ export default (sequelize, DataTypes) => { const TestCase = sequelize.define('testCases', { - name: { - type: DataTypes.STRING, + createdByUser: { allowNull: false, + references: { + key: 'id', + model: 'users' + }, + type: DataTypes.INTEGER, validate: { notNull: true } }, description: { + allowNull: true, + type: DataTypes.STRING + }, + name: { + allowNull: false, type: DataTypes.STRING, - allowNull: true + validate: { + notNull: true + } }, projectId: { - type: DataTypes.INTEGER, + onDelete: 'CASCADE', references: { - model: 'projects', - key: 'id' + key: 'id', + model: 'projects' }, - onDelete: 'CASCADE' + type: DataTypes.INTEGER }, tags: { - type: DataTypes.JSON, - defaultValue: null - }, - createdByUser: { - type: DataTypes.INTEGER, - allowNull: false, - validate: { - notNull: true - }, - references: { - model: 'users', - key: 'id' - } + defaultValue: null, + type: DataTypes.JSON } }); diff --git a/TestCase/Models/TestCaseLog.js b/TestCase/Models/TestCaseLog.js index 4dbddf0..227b465 100644 --- a/TestCase/Models/TestCaseLog.js +++ b/TestCase/Models/TestCaseLog.js @@ -1,33 +1,33 @@ export default (sequelize, DataTypes) => { const TestCaseLogs = sequelize.define('testCaseLogs', { - log: { - type: DataTypes.STRING, + createdByUser: { allowNull: false, + references: { + key: 'id', + model: 'users' + }, + type: DataTypes.INTEGER, validate: { notNull: true } }, - testCaseId: { - type: DataTypes.INTEGER, + log: { allowNull: false, + type: DataTypes.STRING, validate: { notNull: true - }, + } + }, + testCaseId: { + allowNull: false, + onDelete: 'CASCADE', references: { - model: 'testCases', - key: 'id' + key: 'id', + model: 'testCases' }, - onDelete: 'CASCADE' - }, - createdByUser: { type: DataTypes.INTEGER, - allowNull: false, validate: { notNull: true - }, - references: { - model: 'users', - key: 'id' } } }); diff --git a/TestCase/Models/TestExecution/ExecutionSuite.js b/TestCase/Models/TestExecution/ExecutionSuite.js index 8fb55a4..5b96dfc 100644 --- a/TestCase/Models/TestExecution/ExecutionSuite.js +++ b/TestCase/Models/TestExecution/ExecutionSuite.js @@ -1,38 +1,38 @@ export default (sequelize, DataTypes) => { const ExecutionSuite = sequelize.define('executionSuites', { - name: { - type: DataTypes.STRING, + createdByUser: { allowNull: false, + references: { + key: 'id', + model: 'users' + }, + type: DataTypes.INTEGER, validate: { notNull: true } }, description: { + allowNull: true, + type: DataTypes.STRING + }, + name: { + allowNull: false, type: DataTypes.STRING, - allowNull: true + validate: { + notNull: true + } }, projectId: { - type: DataTypes.INTEGER, + onDelete: 'CASCADE', references: { - model: 'projects', - key: 'id' + key: 'id', + model: 'projects' }, - onDelete: 'CASCADE' + type: DataTypes.INTEGER }, tags: { - type: DataTypes.JSON, - defaultValue: null - }, - createdByUser: { - type: DataTypes.INTEGER, - allowNull: false, - validate: { - notNull: true - }, - references: { - model: 'users', - key: 'id' - } + defaultValue: null, + type: DataTypes.JSON } }); diff --git a/TestCase/Models/TestExecution/TestCaseExecutionMapping.js b/TestCase/Models/TestExecution/TestCaseExecutionMapping.js index 93eefca..6fa8466 100644 --- a/TestCase/Models/TestExecution/TestCaseExecutionMapping.js +++ b/TestCase/Models/TestExecution/TestCaseExecutionMapping.js @@ -1,35 +1,35 @@ export default (sequelize, DataTypes) => { const TestCaseExecutionMapping = sequelize.define('testCaseExecutionMappings', { - testCaseId: { - type: DataTypes.INTEGER, + executionSuiteId: { allowNull: false, + onDelete: 'CASCADE', + references: { + key: 'id', + model: 'executionSuites' + }, + type: DataTypes.INTEGER, validate: { notNull: true - }, - references: { - model: 'testCases', - key: 'id' } - // onDelete: "CASCADE", }, - executionSuiteId: { - type: DataTypes.INTEGER, + step: { allowNull: false, + type: DataTypes.INTEGER, validate: { notNull: true - }, + } + }, + testCaseId: { + allowNull: false, references: { - model: 'executionSuites', - key: 'id' + key: 'id', + model: 'testCases' }, - onDelete: 'CASCADE' - }, - step: { type: DataTypes.INTEGER, - allowNull: false, validate: { notNull: true } + // OnDelete: "CASCADE", } }); diff --git a/TestCase/Models/TestParameter.js b/TestCase/Models/TestParameter.js index bd0a4ed..118a815 100644 --- a/TestCase/Models/TestParameter.js +++ b/TestCase/Models/TestParameter.js @@ -1,38 +1,38 @@ export default (sequelize, DataTypes) => { const TestParameter = sequelize.define('testParameters', { - type: { - type: DataTypes.STRING, + method: { allowNull: false, + defaultValue: 'Static', + type: DataTypes.STRING, validate: { notNull: true } }, property: { - type: DataTypes.STRING, allowNull: false, + type: DataTypes.STRING, validate: { notNull: true } }, - method: { - type: DataTypes.STRING, + testStepId: { allowNull: false, + onDelete: 'CASCADE', + references: { + key: 'id', + model: 'testSteps' + }, + type: DataTypes.INTEGER, validate: { notNull: true - }, - defaultValue: 'Static' + } }, - testStepId: { - type: DataTypes.INTEGER, + type: { allowNull: false, + type: DataTypes.STRING, validate: { notNull: true - }, - references: { - model: 'testSteps', - key: 'id' - }, - onDelete: 'CASCADE' + } } }); diff --git a/TestCase/Models/TestStep.js b/TestCase/Models/TestStep.js index a9933f1..b84ee25 100644 --- a/TestCase/Models/TestStep.js +++ b/TestCase/Models/TestStep.js @@ -1,61 +1,61 @@ export default (sequelize, DataTypes) => { const TestStep = sequelize.define('testSteps', { actionEvent: { - type: DataTypes.STRING, allowNull: false, + type: DataTypes.STRING, validate: { notNull: true } }, comment: { - type: DataTypes.STRING, - allowNull: true + allowNull: true, + type: DataTypes.STRING }, - step: { - type: DataTypes.INTEGER, - allowNull: false, - validate: { - notNull: true - } + enable: { + defaultValue: 1, + type: DataTypes.BOOLEAN, + values: [0, 1] }, objectId: { - type: DataTypes.INTEGER, allowNull: true, references: { - model: 'objects', - key: 'id' - } + key: 'id', + model: 'objects' + }, + type: DataTypes.INTEGER + }, + processId: { + onDelete: 'CASCADE', + references: { + key: 'id', + model: 'processes' + }, + type: DataTypes.INTEGER + }, + reusableProcessId: { + onDelete: 'CASCADE', + references: { + key: 'id', + model: 'reusableProcesses' + }, + type: DataTypes.INTEGER }, screenshot: { - type: DataTypes.BOOLEAN, defaultValue: 0, + type: DataTypes.BOOLEAN, values: [0, 1] }, + step: { + allowNull: false, + type: DataTypes.INTEGER, + validate: { + notNull: true + } + }, xpath: { - type: DataTypes.BOOLEAN, defaultValue: 0, - values: [0, 1] - }, - enable: { type: DataTypes.BOOLEAN, - defaultValue: 1, values: [0, 1] - }, - processId: { - type: DataTypes.INTEGER, - references: { - model: 'processes', - key: 'id' - }, - onDelete: 'CASCADE' - }, - reusableProcessId: { - type: DataTypes.INTEGER, - references: { - model: 'reusableProcesses', - key: 'id' - }, - onDelete: 'CASCADE' } }); diff --git a/TestCase/Routes/environment.js b/TestCase/Routes/environment.js index 053fc78..ff878f7 100644 --- a/TestCase/Routes/environment.js +++ b/TestCase/Routes/environment.js @@ -1,14 +1,16 @@ import express from 'express'; + +import { validatePermission } from '#middlewares/permissions.js'; + import { - createEnvironment, - getAllEnvironmentsByTestCase, createColumnForEnvironment, - updateColumnValue, - getAllEnvironmentNamesByTestCase, + createEnvironment, deleteColumnFromEnvironment, - deleteEnvironment + deleteEnvironment, + getAllEnvironmentNamesByTestCase, + getAllEnvironmentsByTestCase, + updateColumnValue } from '../Controllers/environment.js'; -import { validatePermission } from '#middlewares/permissions.js'; const Router = express.Router(); Router.get('/testCase/:testCaseId', validatePermission('Test Case', 'view'), getAllEnvironmentsByTestCase); diff --git a/TestCase/Routes/executionHistory.js b/TestCase/Routes/executionHistory.js index 6f49a99..04b11d1 100644 --- a/TestCase/Routes/executionHistory.js +++ b/TestCase/Routes/executionHistory.js @@ -1,6 +1,8 @@ import express from 'express'; -import { getAllExecutionHistoryByTestCase, deleteExecutionHistoryById, deleteExecutionHistoryByTestCase, getExecutionHistoryById } from '../Controllers/executionHistory.js'; + import { validatePermission } from '#middlewares/permissions.js'; + +import { deleteExecutionHistoryById, deleteExecutionHistoryByTestCase, getAllExecutionHistoryByTestCase, getExecutionHistoryById } from '../Controllers/executionHistory.js'; const Router = express.Router(); Router.delete('/:executionHistoryId', validatePermission('Execute', 'delete'), deleteExecutionHistoryById); diff --git a/TestCase/Routes/executionSuiteRoutes.js b/TestCase/Routes/executionSuiteRoutes.js index 94034b2..ecb55a0 100644 --- a/TestCase/Routes/executionSuiteRoutes.js +++ b/TestCase/Routes/executionSuiteRoutes.js @@ -1,15 +1,17 @@ import express from 'express'; + +import { validatePermission } from '#middlewares/permissions.js'; + import { addExecutionSuite, addTestCaseToExecutionSuite, deleteExecutionSuite, + editExecutionSuite, getAllExecutionSuite, - getTestCaseByExecutionSuiteId, - removeTestCaseFromExecutionSuite, getExecutionSuiteDetailsById, - editExecutionSuite + getTestCaseByExecutionSuiteId, + removeTestCaseFromExecutionSuite } from '../Controllers/executionSuiteController.js'; -import { validatePermission } from '#middlewares/permissions.js'; const Router = express.Router(); Router.post('/', validatePermission('Execution Suite', 'add'), addExecutionSuite); diff --git a/TestCase/Routes/machineRoutes.js b/TestCase/Routes/machineRoutes.js index 05babd1..674a6bd 100644 --- a/TestCase/Routes/machineRoutes.js +++ b/TestCase/Routes/machineRoutes.js @@ -1,6 +1,8 @@ import express from 'express'; -import { addMachine, getAllMachine, removeMachine } from '../Controllers/machineController.js'; + import { validatePermission } from '#middlewares/permissions.js'; + +import { addMachine, getAllMachine, removeMachine } from '../Controllers/machineController.js'; const Router = express.Router(); Router.get('/', validatePermission('Test Case', 'view'), getAllMachine); Router.post('/', addMachine); diff --git a/TestCase/Routes/object.js b/TestCase/Routes/object.js index 61faad3..4d8b36d 100644 --- a/TestCase/Routes/object.js +++ b/TestCase/Routes/object.js @@ -1,17 +1,19 @@ import express from 'express'; + +import { validatePermission } from '#middlewares/permissions.js'; + import { - saveObject, - updateObject, + createObjectLog, deleteObject, + deleteObjectLocator, getAllObject, getObjectDetailsById, - saveObjectLocator, getObjectLocatorsByObjectId, - deleteObjectLocator, getObjectLogsByObjectId, - createObjectLog + saveObject, + saveObjectLocator, + updateObject } from '../Controllers/object.js'; -import { validatePermission } from '#middlewares/permissions.js'; const Router = express.Router(); Router.post('/', validatePermission('Test Case', 'add'), saveObject); diff --git a/TestCase/Routes/reusableProcess.js b/TestCase/Routes/reusableProcess.js index 47b7976..b7436c3 100644 --- a/TestCase/Routes/reusableProcess.js +++ b/TestCase/Routes/reusableProcess.js @@ -1,16 +1,18 @@ import express from 'express'; + +import { validatePermission } from '#middlewares/permissions.js'; + import { - getAllReusableProcess, - saveReusableProcess, - updateReusableProcess, + convertToReusableProcess, + createReusableProcessLog, deleteReusableProcess, + getAllReusableProcess, getReusableProcessDetailsById, - getTestStepByReusableProcess, - createReusableProcessLog, getReusableProcessLogsById, - convertToReusableProcess + getTestStepByReusableProcess, + saveReusableProcess, + updateReusableProcess } from '../Controllers/reusableProcessController.js'; -import { validatePermission } from '#middlewares/permissions.js'; const Router = express.Router(); Router.post('/', validatePermission('Reusable Process', 'add'), saveReusableProcess); diff --git a/TestCase/Routes/testCase.js b/TestCase/Routes/testCase.js index 4dc1c26..58f07dd 100644 --- a/TestCase/Routes/testCase.js +++ b/TestCase/Routes/testCase.js @@ -1,18 +1,20 @@ import express from 'express'; + +import { validatePermission } from '#middlewares/permissions.js'; + import { - getAllTestCase, - saveTestCase, - updateTestCase, + createTestCaseLog, + deleteProcess, deleteTestCase, + getAllTestCase, getTestCaseDetailsById, + getTestCaseLogsById, getTestStepByTestCase, saveProcess, + saveTestCase, updateProcess, - deleteProcess, - getTestCaseLogsById, - createTestCaseLog + updateTestCase } from '../Controllers/testCaseController.js'; -import { validatePermission } from '#middlewares/permissions.js'; const Router = express.Router(); Router.post('/', validatePermission('Test Case', 'add'), saveTestCase); diff --git a/TestCase/Routes/testStepRoutes.js b/TestCase/Routes/testStepRoutes.js index bd9fe24..c401502 100644 --- a/TestCase/Routes/testStepRoutes.js +++ b/TestCase/Routes/testStepRoutes.js @@ -1,17 +1,18 @@ import express from 'express'; -import { saveTestStep, updateTestStep, deleteTestStep } from '../Controllers/testStepController.js'; -// import { validatePermission } from "#middlewares/permissions.js"; + +import { deleteTestStep, saveTestStep, updateTestStep } from '../Controllers/testStepController.js'; +// Import { validatePermission } from "#middlewares/permissions.js"; const Router = express.Router(); Router.post('/', saveTestStep); Router.put( '/:testStepId', - // validatePermission("Test Case", "edit"), + // ValidatePermission("Test Case", "edit"), updateTestStep ); Router.delete( '/:testStepId', - // validatePermission("Test Case", "edit"), + // ValidatePermission("Test Case", "edit"), deleteTestStep ); export default Router; diff --git a/TestCase/Validations/environment.js b/TestCase/Validations/environment.js index ad179bf..b87568a 100644 --- a/TestCase/Validations/environment.js +++ b/TestCase/Validations/environment.js @@ -5,7 +5,7 @@ export const nameTestCaseId = joi.object({ testCaseId: joi.number().integer().required() }); export const updateColumnValidation = joi.object({ + envId: joi.number().integer().required(), name: joi.string().min(3).max(100).required(), - value: joi.string(), - envId: joi.number().integer().required() + value: joi.string() }); diff --git a/TestCase/Validations/object.js b/TestCase/Validations/object.js index 852d087..327b86d 100644 --- a/TestCase/Validations/object.js +++ b/TestCase/Validations/object.js @@ -1,14 +1,14 @@ import joi from '@hapi/joi'; export const updateObjectValidation = joi.object({ - name: joi.string().min(3).max(100).required(), - tags: joi.array().allow(null, ''), description: joi.string().allow(null, '').required(), - objectId: joi.number().integer().required() + name: joi.string().min(3).max(100).required(), + objectId: joi.number().integer().required(), + tags: joi.array().allow(null, '') }); export const saveObjectLocatorValidation = joi.object({ locator: joi.string().required(), - type: joi.string().required(), - objectId: joi.number().integer().required() + objectId: joi.number().integer().required(), + type: joi.string().required() }); diff --git a/TestCase/Validations/reusableProcess.js b/TestCase/Validations/reusableProcess.js index 21229aa..3826c64 100644 --- a/TestCase/Validations/reusableProcess.js +++ b/TestCase/Validations/reusableProcess.js @@ -1,8 +1,8 @@ import joi from '@hapi/joi'; export const updateReusableProcessValidation = joi.object({ - name: joi.string().min(3).max(100).required(), - tags: joi.array().allow(null, ''), description: joi.string().allow(null, ''), - reusableProcessId: joi.number().integer().required() + name: joi.string().min(3).max(100).required(), + reusableProcessId: joi.number().integer().required(), + tags: joi.array().allow(null, '') }); diff --git a/TestCase/Validations/testCase.js b/TestCase/Validations/testCase.js index 61347a6..ca696f6 100644 --- a/TestCase/Validations/testCase.js +++ b/TestCase/Validations/testCase.js @@ -1,26 +1,26 @@ import joi from '@hapi/joi'; export const updateTestCaseValidation = joi.object({ + description: joi.string().allow(null, '').required(), name: joi.string().min(3).max(100).required(), tags: joi.array().allow(null, ''), - description: joi.string().allow(null, '').required(), testCaseId: joi.number().integer().required() }); export const saveProcesValidation = joi.object({ - step: joi.number().integer().required(), - name: joi.string().min(3).max(100).required(), comment: joi.string().allow(null, '').required(), - testCaseId: joi.number().integer().required(), - reusableProcessId: joi.number().integer(), enable: joi.boolean().required(), + name: joi.string().min(3).max(100).required(), + reusableProcessId: joi.number().integer(), + step: joi.number().integer().required(), + testCaseId: joi.number().integer().required(), testSteps: joi.array().allow(null, '') }); export const updateProcessValidation = joi.object({ - name: joi.string().min(3).max(100), comment: joi.string().allow(null, ''), + enable: joi.boolean().required(), + name: joi.string().min(3).max(100), processId: joi.number().integer(), - reusableProcessId: joi.number().integer(), - enable: joi.boolean().required() + reusableProcessId: joi.number().integer() }); diff --git a/TestCase/Validations/testStep.js b/TestCase/Validations/testStep.js index 58ebf21..17f519b 100644 --- a/TestCase/Validations/testStep.js +++ b/TestCase/Validations/testStep.js @@ -1,25 +1,25 @@ import joi from '@hapi/joi'; export const saveTestStepValidation = joi.object({ - processId: joi.number().integer(), + actionEvent: joi.string().required(), + comment: joi.string().allow(null, '').required(), + enable: joi.boolean().required(), objectId: joi.number().integer().allow(null), - reusableProcessId: joi.number().integer(), - step: joi.number().integer().required(), parameters: joi.array().allow(null), + processId: joi.number().integer(), + reusableProcessId: joi.number().integer(), screenshot: joi.boolean().required(), - enable: joi.boolean().required(), - xpath: joi.boolean(), - comment: joi.string().allow(null, '').required(), - actionEvent: joi.string().required() + step: joi.number().integer().required(), + xpath: joi.boolean() }); export const updateTestStepValidation = joi.object({ - testStepId: joi.number().integer().required(), + actionEvent: joi.string().required(), + comment: joi.string().allow(null, '').required(), + enable: joi.boolean().required(), objectId: joi.number().integer().allow(null), parameters: joi.array().allow(null), screenshot: joi.boolean().required(), - enable: joi.boolean().required(), - xpath: joi.boolean(), - comment: joi.string().allow(null, '').required(), - actionEvent: joi.string().required() + testStepId: joi.number().integer().required(), + xpath: joi.boolean() }); diff --git a/User/Controllers/authController.js b/User/Controllers/authController.js index a9154b9..9eda4d7 100644 --- a/User/Controllers/authController.js +++ b/User/Controllers/authController.js @@ -1,14 +1,16 @@ -import db from '#utils/dataBaseConnection.js'; -import { createToken, getTokenError } from '#utils/jwt.js'; -import { sendMail } from '#utils/Mail/nodeMailer.js'; import pkg from 'jsonwebtoken'; -import getError from '#utils/error.js'; import moment from 'moment'; + +import errorContstants from '#constants/error.js'; +import successConstants from '#constants/success.js'; import { createBucket } from '#storage/Service/awsService.js'; +import db from '#utils/dataBaseConnection.js'; +import getError from '#utils/error.js'; +import { createToken, getTokenError } from '#utils/jwt.js'; +import { sendMail } from '#utils/Mail/nodeMailer.js'; + import { dropDatabase, syncDatabase } from '../Service/database.js'; -import errorContstants from '#constants/error.js'; import { loginWithCredentals } from '../Service/user.js'; -import successConstants from '#constants/success.js'; const { verify } = pkg; // Main @@ -17,9 +19,11 @@ const Unverified = db.unverifieds; // Tenant const User = db.users; -// const Role = db.roles; -// const Permission = db.permissions; -// const UserRole = db.userRoles; +/* + * Const Role = db.roles; + * const Permission = db.permissions; + * const UserRole = db.userRoles; + */ const register = async (req, res) => { /* #swagger.tags = ["Auth"] */ @@ -30,7 +34,7 @@ const register = async (req, res) => { const tenantName = process.env.MULTI_TENANT === 'false' ? process.env.DATABASE_NAME : email.replace(/[^a-zA-Z0-9 ]/g, '').toLowerCase(); await Customer.schema(process.env.DATABASE_PREFIX + process.env.DATABASE_NAME) - .create({ email, tenantName, admin: true }, { transaction }) + .create({ admin: true, email, tenantName }, { transaction }) .catch((e) => { console.error(e); throw new Error('Customer already exist'); @@ -38,8 +42,8 @@ const register = async (req, res) => { const token = createToken({ email }, process.env.JWT_VERIFICATION_SECRET); await Unverified.schema(process.env.DATABASE_PREFIX + process.env.DATABASE_NAME).create( { - name, email, + name, password, token }, @@ -98,10 +102,10 @@ const verifyCustomer = async (req, res) => { if (data) { if (unverifiedUser) { await Unverified.schema(process.env.DATABASE_PREFIX + process.env.DATABASE_NAME).destroy({ + transaction, where: { email - }, - transaction + } }); if (tenantName !== process.env.DATABASE_NAME) { @@ -116,16 +120,15 @@ const verifyCustomer = async (req, res) => { } await User.schema(database).create({ - name, email, + name, password, verifiedAt: moment() }); return res.status(200).json({ message: successConstants.EMAIL_VERIFICATION_SUCCESSFULL }); - } else { - return res.status(500).json({ error: errorContstants.EMAIL_ALREADY_VERIFIED }); } + return res.status(500).json({ error: errorContstants.EMAIL_ALREADY_VERIFIED }); } }); } catch (error) { @@ -153,7 +156,7 @@ const verifyUser = async (req, res) => { if (user) { if (user.verifiedAt) throw new Error(errorContstants.EMAIL_ALREADY_VERIFIED); await User.schema(database).update( - { verifiedAt: new Date(), active: true }, + { active: true, verifiedAt: new Date() }, { where: { email: data.email @@ -161,9 +164,8 @@ const verifyUser = async (req, res) => { } ); return res.status(200).json({ message: successConstants.EMAIL_VERIFICATION_SUCCESSFULL }); - } else { - throw new Error(errorContstants.RECORD_NOT_FOUND); } + throw new Error(errorContstants.RECORD_NOT_FOUND); } } catch (error) { getError(error, res, 'Email Verification'); @@ -188,7 +190,7 @@ const resetPassword = async (req, res) => { } ); if (updatedUser[0]) return res.status(200).json({ message: successConstants.PASSWORD_RESET_SUCCESSFULL }); - else throw new Error(errorContstants.RECORD_NOT_FOUND); + throw new Error(errorContstants.RECORD_NOT_FOUND); } } catch (error) { getError(error, res, 'Password Reset'); @@ -214,22 +216,22 @@ const sendResetPasswordMail = async (req, res) => { } }; -const refreshToken = async (req, res) => { +const refreshToken = (req, res) => { /* #swagger.tags = ["Auth"] */ - const token = req.body.token; + const { token } = req.body; if (!token) return res.status(401).json({ error: errorContstants.REFRESH_TOKEN_NOT_FOUND }); try { const data = verify(token, process.env.JWT_REFRESH_SECRET); if (data) { - const tokenData = { id: data.id, email: data.email }; + const tokenData = { email: data.email, id: data.id }; const accessToken = createToken(tokenData, process.env.JWT_ACCESS_SECRET, process.env.JWT_ACCESS_EXPIRATION); - const refreshToken = createToken(tokenData, process.env.JWT_REFRESH_SECRET, process.env.JWT_REFRESH_EXPIRATION); - return res.status(200).json({ accessToken, refreshToken }); + const refreshedToken = createToken(tokenData, process.env.JWT_REFRESH_SECRET, process.env.JWT_REFRESH_EXPIRATION); + return res.status(200).json({ accessToken, refreshToken: refreshedToken }); } } catch (e) { return res.status(401).json({ error: getTokenError(e, 'Refresh') }); } }; -export { login, register, verifyCustomer, verifyUser, resetPassword, sendResetPasswordMail, refreshToken }; +export { login, refreshToken, register, resetPassword, sendResetPasswordMail, verifyCustomer, verifyUser }; diff --git a/User/Controllers/roleController.js b/User/Controllers/roleController.js index 4ae9f08..63fd3c9 100644 --- a/User/Controllers/roleController.js +++ b/User/Controllers/roleController.js @@ -1,27 +1,29 @@ +import errorContstants from '#constants/error.js'; +import { permissionList } from '#constants/permission.js'; import db from '#utils/dataBaseConnection.js'; import getError from '#utils/error.js'; +import { idValidation, nameValidation } from '#validations/index.js'; + import { updateNameValidation, updatePermissionValidation } from '../Validations/role.js'; -import { nameValidation, idValidation } from '#validations/index.js'; -import { permissionList } from '#constants/permission.js'; -import errorContstants from '#constants/error.js'; const Role = db.roles; const UserRole = db.userRoles; const Permission = db.permissions; const getAllRole = async (req, res) => { - /* #swagger.tags = ["Role"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Role"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const roles = await Role.schema(req.database).findAll({ include: [ { - model: Permission.schema(req.database), - attributes: ['id', 'name', 'view', 'add', 'edit', 'delete'] + attributes: ['id', 'name', 'view', 'add', 'edit', 'delete'], + model: Permission.schema(req.database) } ] }); - // const temp = pageInfo(roles, req.query); + // Const temp = pageInfo(roles, req.query); return res.status(200).json(roles); } catch (err) { getError(err, res); @@ -29,9 +31,10 @@ const getAllRole = async (req, res) => { }; const saveRole = async (req, res) => { - /* #swagger.tags = ["Role"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Role"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { error } = nameValidation.validate(req.body); @@ -46,14 +49,15 @@ const saveRole = async (req, res) => { }; const updateRole = async (req, res) => { - /* #swagger.tags = ["Role"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Role"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const roleId = req.params.roleId; - const name = req.body.name; - const { error } = updateNameValidation.validate({ roleId, name }); + const { roleId } = req.params; + const { name } = req.body; + const { error } = updateNameValidation.validate({ name, roleId }); if (error) throw new Error(error.details[0].message); const updatedRole = await Role.schema(req.database).update( @@ -68,20 +72,20 @@ const updateRole = async (req, res) => { if (updatedRole[0]) { const role = await Role.schema(req.database).findByPk(roleId); return res.status(200).json({ ...role, message: 'Role Updated Successfully!' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (err) { getError(err, res); } }; const deleteRole = async (req, res) => { - /* #swagger.tags = ["Role"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Role"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const roleId = req.params.roleId; + const { roleId } = req.params; const { error } = idValidation.validate({ id: roleId }); if (error) throw new Error(error.details[0].message); @@ -100,49 +104,45 @@ const deleteRole = async (req, res) => { }); if (deletedRole > 0) { return res.status(200).json({ message: 'Role deleted successfully' }); - } else { - return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } + return res.status(400).json({ error: errorContstants.RECORD_NOT_FOUND }); } catch (err) { getError(err, res); } }; const updateRolePermission = async (req, res) => { - /* #swagger.tags = ["Role"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Role"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const roleId = req.params.roleId; + const { roleId } = req.params; const { error } = idValidation.validate({ id: roleId }); if (error) throw new Error(error.details[0].message); - const check = permissionList.some((el) => { - return req.body.some((el1) => { - return el.name === el1.name; - }); - }); + const check = permissionList.some((el) => req.body.some((el1) => el.name === el1.name)); if (check) { const payload = [...req.body].map((el) => { - const { error } = updatePermissionValidation.validate({ + const { error: validationError } = updatePermissionValidation.validate({ add: el.add, - edit: el.edit, - view: el.view, delete: el.delete, - name: el.name + edit: el.edit, + name: el.name, + view: el.view }); - if (error) throw new Error(error.details[0].message); + if (validationError) throw new Error(validationError.details[0].message); return { add: el.add, - edit: el.edit, - view: el.view, delete: el.delete, + edit: el.edit, name: el.name, - roleId + roleId, + view: el.view }; }); @@ -151,30 +151,30 @@ const updateRolePermission = async (req, res) => { }); const permissions = await Permission.schema(req.database).bulkCreate(payload); return res.status(200).json(permissions); - } else { - return res.status(400).json({ error: errorContstants.INVALID_PERMISSION }); } + return res.status(400).json({ error: errorContstants.INVALID_PERMISSION }); } catch (error) { getError(error, res); } }; const getUserRole = async (req, res) => { - /* #swagger.tags = ["Role"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Role"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const userId = req.params.userId; + const { userId } = req.params; const { error } = idValidation.validate({ id: userId }); if (error) throw new Error(error.details[0].message); const roles = await UserRole.schema(req.database).findAll({ - where: { userId }, include: [ { - model: Role.schema(req.database), - attributes: ['name'] + attributes: ['name'], + model: Role.schema(req.database) } - ] + ], + where: { userId } }); const tempRole = roles.map((el) => { const temp = { ...el.dataValues, name: el.dataValues.role.name }; @@ -189,11 +189,12 @@ const getUserRole = async (req, res) => { }; const updateUserRole = async (req, res) => { - /* #swagger.tags = ["Role"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Role"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const userId = req.params.userId; + const { userId } = req.params; const { error } = idValidation.validate({ id: userId }); if (error) throw new Error(error.details[0].message); @@ -208,4 +209,4 @@ const updateUserRole = async (req, res) => { } }; -export { saveRole, updateRole, getAllRole, deleteRole, updateRolePermission, updateUserRole, getUserRole }; +export { deleteRole, getAllRole, getUserRole, saveRole, updateRole, updateRolePermission, updateUserRole }; diff --git a/User/Controllers/superAdminController.js b/User/Controllers/superAdminController.js index e2494cc..bdc1357 100644 --- a/User/Controllers/superAdminController.js +++ b/User/Controllers/superAdminController.js @@ -1,12 +1,15 @@ -import getError from '#utils/error.js'; -import { syncDatabase, deleteCustomer, getCachedKeys } from '../Service/database.js'; import _ from 'lodash'; + import cache from '#utils/cache.js'; +import getError from '#utils/error.js'; + +import { deleteCustomer, getCachedKeys, syncDatabase } from '../Service/database.js'; const deleteCustomerByAdmin = async (req, res) => { - /* #swagger.tags = ["Super Admin"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Super Admin"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { customerEmail } = req.body; await deleteCustomer(customerEmail); @@ -17,9 +20,10 @@ const deleteCustomerByAdmin = async (req, res) => { }; const syncTenant = async (req, res) => { - /* #swagger.tags = ["Super Admin"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["Super Admin"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { customerEmail, force = false, alter = false } = req.body; const tenant = customerEmail.replace(/[^a-zA-Z0-9 ]/g, '').toLowerCase(); @@ -30,10 +34,11 @@ const syncTenant = async (req, res) => { } }; -const getAllSession = async (req, res) => { - /* #swagger.tags = ["Super Admin"] - #swagger.security = [{"apiKeyAuth": []}] - */ +const getAllSession = (req, res) => { + /* + * #swagger.tags = ["Super Admin"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const sessions = getCachedKeys(); const sessionObj = sessions @@ -53,10 +58,11 @@ const getAllSession = async (req, res) => { } }; -const terminateSession = async (req, res) => { - /* #swagger.tags = ["Super Admin"] - #swagger.security = [{"apiKeyAuth": []}] - */ +const terminateSession = (req, res) => { + /* + * #swagger.tags = ["Super Admin"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { tenant, email } = req.body; if (process.env.JWT_ACCESS_CACHE) cache.del(`accesstoken_${tenant}_${email}`); @@ -66,4 +72,4 @@ const terminateSession = async (req, res) => { } }; -export { deleteCustomerByAdmin, syncTenant, getAllSession, terminateSession }; +export { deleteCustomerByAdmin, getAllSession, syncTenant, terminateSession }; diff --git a/User/Controllers/userController.js b/User/Controllers/userController.js index 7658bd9..443a9c5 100644 --- a/User/Controllers/userController.js +++ b/User/Controllers/userController.js @@ -1,11 +1,13 @@ -import db from '#utils/dataBaseConnection.js'; -import getError from '#utils/error.js'; import bcrypt from 'bcryptjs'; -import { sendMail } from '#utils/Mail/nodeMailer.js'; -import { s3, uploadFile } from '#storage/Service/awsService.js'; + import errorContstants from '#constants/error.js'; import successConstants from '#constants/success.js'; +import { s3, uploadFile } from '#storage/Service/awsService.js'; import cache from '#utils/cache.js'; +import db from '#utils/dataBaseConnection.js'; +import getError from '#utils/error.js'; +import { sendMail } from '#utils/Mail/nodeMailer.js'; + import { deleteCustomer } from '../Service/database.js'; const User = db.users; @@ -16,16 +18,15 @@ const Role = db.roles; const Permission = db.permissions; const getTeam = async (req, res) => { - /* #swagger.tags = ["User"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["User"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const team = await User.schema(req.database).findAll({ attributes: ['id', 'name', 'email', 'profileImage', 'verifiedAt', 'deletedAt', 'active', 'defaultProjectId'] }); - const filteredTeam = team.filter((el) => { - return el.id !== req.user.id; - }); + const filteredTeam = team.filter((el) => el.id !== req.user.id); const teamWithImages = await filteredTeam.map(async (user) => { let base64ProfileImage = ''; @@ -61,9 +62,7 @@ const getTeam = async (req, res) => { }; } }); - Promise.all(teamWithImages).then((data) => { - return res.status(200).json(data); - }).catch((err) => { + Promise.all(teamWithImages).then((data) => res.status(200).json(data)).catch((err) => { throw new Error(err); }); } catch (error) { @@ -72,12 +71,13 @@ const getTeam = async (req, res) => { }; const addUser = async (req, res) => { - /* #swagger.tags = ["User"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["User"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { name, email, password } = req.body; - const database = req.database; + const { database } = req; await Customer.schema(process.env.DATABASE_PREFIX + process.env.DATABASE_NAME) .create({ email, tenantName: req.user.tenant }) @@ -88,18 +88,18 @@ const addUser = async (req, res) => { const hash = await bcrypt.hash(password, 8); const user = await User.schema(req.database).create({ - name, + active: false, email, - password: hash, - active: false + name, + password: hash }); sendMail({ email, name, tenant: database }, 'addUser'); return res.status(200).json({ - id: user.id, - name, email, - message: 'User added, Verify user\'s email to login' + id: user.id, + message: 'User added, Verify user\'s email to login', + name }); } catch (error) { getError(error, res); @@ -107,12 +107,13 @@ const addUser = async (req, res) => { }; const resendVerificationEmail = async (req, res) => { - /* #swagger.tags = ["User"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["User"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { email } = req.body; - const database = req.database; + const { database } = req; const user = await User.schema(database).findOne({ where: { email } @@ -128,11 +129,12 @@ const resendVerificationEmail = async (req, res) => { }; const deleteUser = async (req, res) => { - /* #swagger.tags = ["User"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["User"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const userId = req.params.userId; + const { userId } = req.params; const user = await User.schema(req.database).findByPk(userId); if (req.user.tenant === user.email.replace(/[^a-zA-Z0-9 ]/g, '').toLowerCase()) throw new Error('Cannot Delete Customer Admin'); @@ -162,9 +164,10 @@ const deleteUser = async (req, res) => { }; const deleteCustomerUser = async (req, res) => { - /* #swagger.tags = ["User"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["User"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { if (!req.user.customerAdmin) return res.status(401).json({ message: 'Only customer admin can perform this operation!' }); @@ -176,9 +179,10 @@ const deleteCustomerUser = async (req, res) => { }; const changePassword = async (req, res) => { - /* #swagger.tags = ["User"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["User"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const { oldPassword, newPassword } = req.body; @@ -194,37 +198,39 @@ const changePassword = async (req, res) => { } ); if (updatedUser[0]) return res.status(200).json({ message: successConstants.UPDATED }); - else throw new Error(errorContstants.RECORD_NOT_FOUND); + throw new Error(errorContstants.RECORD_NOT_FOUND); } catch (error) { getError(error, res); } }; const changeDetails = async (req, res) => { - /* #swagger.tags = ["User"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["User"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const userId = req.params.userId || req.user.id; - const body = req.user.id === userId ? req.body : { active: req.body.active } || {}; + const body = req.user.id === userId ? req.body : { active: req.body.active }; delete body.password; - const updatedUser = await User.schema(req.database).update(body, { + const updatedUser = await User.schema(req.database).update(body || {}, { where: { id: userId } }); if (updatedUser[0]) return res.status(200).json({ message: successConstants.UPDATED }); - else throw new Error(errorContstants.RECORD_NOT_FOUND); + throw new Error(errorContstants.RECORD_NOT_FOUND); } catch (error) { getError(error, res); } }; const uploadProfileImage = async (req, res) => { - /* #swagger.tags = ["User"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["User"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { const file = req.files.image; if (!file) throw new Error('Inavlid Image'); @@ -241,43 +247,44 @@ const uploadProfileImage = async (req, res) => { } ); return res.status(200).json({ message: successConstants.UPDATED }); - } else throw new Error('Unable to upload profile image!'); + } throw new Error('Unable to upload profile image!'); } catch (error) { getError(error, res); } }; const getUserDetailsByEmail = async (req, res) => { - /* #swagger.tags = ["User"] - #swagger.security = [{"apiKeyAuth": []}] - */ + /* + * #swagger.tags = ["User"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { - const database = req.user.database; + const { database } = req.user; const email = req.body.email || req.user.email; const customer = await Customer.schema(process.env.DATABASE_PREFIX + process.env.DATABASE_NAME).findOne({ where: { email } }); const user = await User.schema(database).findOne({ - where: { email }, include: [ { - model: UserRole.schema(database), attributes: ['roleId'], include: [ { - model: Role.schema(database), attributes: ['name'], include: [ { - model: Permission.schema(database), - attributes: ['name', 'view', 'add', 'edit', 'delete'] + attributes: ['name', 'view', 'add', 'edit', 'delete'], + model: Permission.schema(database) } - ] + ], + model: Role.schema(database) } - ] + ], + model: UserRole.schema(database) } - ] + ], + where: { email } }); if (!user) throw new Error(errorContstants.RECORD_NOT_FOUND); @@ -314,24 +321,25 @@ const getUserDetailsByEmail = async (req, res) => { } return res.status(200).json({ + customerAdmin, + defaultProjectId, + email, id, name, - email, profileImage: profileImage ? base64ProfileImage : '', - customerAdmin, - defaultProjectId, - verifiedAt, - roles: newRoles + roles: newRoles, + verifiedAt }); } catch (error) { getError(error, res); } }; -const logout = async (req, res) => { - /* #swagger.tags = ["User"] - #swagger.security = [{"apiKeyAuth": []}] - */ +const logout = (req, res) => { + /* + * #swagger.tags = ["User"] + * #swagger.security = [{"apiKeyAuth": []}] + */ try { if (process.env.JWT_ACCESS_CACHE) cache.del(`accesstoken_${req.user.tenant}_${req.user.email}`); return res.status(200).json({ message: 'Logout Successfull' }); @@ -340,58 +348,60 @@ const logout = async (req, res) => { } }; -// const toggleUserActiveInactive = async (req, res) => { +// Const toggleUserActiveInactive = async (req, res) => { // /* #swagger.tags = ["User"] // #swagger.security = [{"apiKeyAuth": []}] // */ -// try { -// const userId = req.params.userId; -// const active = req.body.active; - -// const updatedUser = await User.schema(req.database).update(req.body, { -// where: { -// id: userId, -// }, -// }); -// if (updatedUser[0]) return res.status(200).json({ message: `Marked User as ${active ? "Active" : "Inactive"}` }); -// else throw new Error(errorContstants.RECORD_NOT_FOUND); -// } catch (error) { -// getError(error, res); -// } -// }; - -// const myStatus = async (req, res) => { +// Try { +// Const userId = req.params.userId; +// Const active = req.body.active; + +/* + * Const updatedUser = await User.schema(req.database).update(req.body, { + * where: { + * id: userId, + * }, + * }); + * if (updatedUser[0]) return res.status(200).json({ message: `Marked User as ${active ? "Active" : "Inactive"}` }); + * else throw new Error(errorContstants.RECORD_NOT_FOUND); + * } catch (error) { + * getError(error, res); + * } + * }; + */ + +// Const myStatus = async (req, res) => { // /* #swagger.tags = ["User"] // #swagger.security = [{"apiKeyAuth": []}] // */ -// try { -// const user = await User.schema(req.database).findOne({ -// where: { email: req.user.email }, +// Try { +// Const user = await User.schema(req.database).findOne({ +// Where: { email: req.user.email }, // }); -// if (!user.active) return res.status(403).json({ error: errorContstants.ACCOUNT_INACTIVE }); -// const customer = await Customer.schema(process.env.DATABASE_PREFIX + process.env.DATABASE_NAME).findOne({ -// where: { email: req.user.email }, +// If (!user.active) return res.status(403).json({ error: errorContstants.ACCOUNT_INACTIVE }); +// Const customer = await Customer.schema(process.env.DATABASE_PREFIX + process.env.DATABASE_NAME).findOne({ +// Where: { email: req.user.email }, // }); -// if (customer.blocked) return res.status(403).json({ error: errorContstants.ACCOUNT_BLOCKED }); +// If (customer.blocked) return res.status(403).json({ error: errorContstants.ACCOUNT_BLOCKED }); -// return res.status(200).json("Active"); -// } catch (error) { -// getError(error, res); -// } -// }; +/* + * Return res.status(200).json("Active"); + * } catch (error) { + * getError(error, res); + * } + * }; + */ export { addUser, - deleteUser, - changePassword, changeDetails, - getTeam, - resendVerificationEmail, + changePassword, deleteCustomerUser, - uploadProfileImage, + deleteUser, + getTeam, + getUserDetailsByEmail, logout, - getUserDetailsByEmail - // toggleUserActiveInactive, - // myStatus, + resendVerificationEmail, + uploadProfileImage }; diff --git a/User/Models/Customer.js b/User/Models/Customer.js index 7c10dd7..5545a8c 100644 --- a/User/Models/Customer.js +++ b/User/Models/Customer.js @@ -3,28 +3,28 @@ export default (sequelize, DataTypes) => { const Customer = sequelize.define( 'customers', { + admin: { + defaultValue: 0, + type: DataTypes.BOOLEAN, + values: [0, 1] + }, + blocked: { + defaultValue: 0, + type: DataTypes.BOOLEAN, + values: [0, 1] + }, email: { - type: DataTypes.STRING, allowNull: false, + type: DataTypes.STRING, unique: 'email', validate: { isEmail: true, notNull: true } }, - blocked: { - type: DataTypes.BOOLEAN, - defaultValue: 0, - values: [0, 1] - }, - admin: { - type: DataTypes.BOOLEAN, - defaultValue: 0, - values: [0, 1] - }, tenantName: { - type: DataTypes.STRING, allowNull: false, + type: DataTypes.STRING, validate: { notNull: true } @@ -32,7 +32,7 @@ export default (sequelize, DataTypes) => { }, { hooks: { - afterFind: function (model) { + afterFind: function afterFind (model) { if (!Array.isArray(model)) { if (model.dataValues.blocked) throw new Error(errorContstants.ACCOUNT_BLOCKED); } diff --git a/User/Models/RolePermission/Permission.js b/User/Models/RolePermission/Permission.js index e6b1cbe..e42f4f9 100644 --- a/User/Models/RolePermission/Permission.js +++ b/User/Models/RolePermission/Permission.js @@ -1,44 +1,44 @@ export default (sequelize, DataTypes) => { const Permission = sequelize.define('permissions', { + add: { + defaultValue: 0, + type: DataTypes.BOOLEAN, + values: [0, 1] + }, + + delete: { + defaultValue: 0, + type: DataTypes.BOOLEAN, + values: [0, 1] + }, + edit: { + defaultValue: 0, + type: DataTypes.BOOLEAN, + values: [0, 1] + }, name: { - type: DataTypes.STRING, allowNull: false, + type: DataTypes.STRING, unique: false, validate: { notNull: true } }, - roleId: { - type: DataTypes.INTEGER, allowNull: false, - validate: { - notNull: true - }, + onDelete: 'CASCADE', references: { - model: 'roles', - key: 'id' + key: 'id', + model: 'roles' }, - onDelete: 'CASCADE' + type: DataTypes.INTEGER, + validate: { + notNull: true + } }, view: { - type: DataTypes.BOOLEAN, defaultValue: 0, - values: [0, 1] - }, - add: { type: DataTypes.BOOLEAN, - defaultValue: 0, - values: [0, 1] - }, - edit: { - type: DataTypes.BOOLEAN, - defaultValue: 0, - values: [0, 1] - }, - delete: { - type: DataTypes.BOOLEAN, - defaultValue: 0, values: [0, 1] } }); diff --git a/User/Models/RolePermission/Role.js b/User/Models/RolePermission/Role.js index 1d70d94..f42f2d5 100644 --- a/User/Models/RolePermission/Role.js +++ b/User/Models/RolePermission/Role.js @@ -1,8 +1,8 @@ export default (sequelize, DataTypes) => { const Role = sequelize.define('roles', { name: { - type: DataTypes.STRING, allowNull: false, + type: DataTypes.STRING, unique: 'name', validate: { notNull: true diff --git a/User/Models/RolePermission/UserRole.js b/User/Models/RolePermission/UserRole.js index 7476f8f..310b16f 100644 --- a/User/Models/RolePermission/UserRole.js +++ b/User/Models/RolePermission/UserRole.js @@ -1,28 +1,28 @@ export default (sequelize, DataTypes) => { const UserRole = sequelize.define('userRoles', { - userId: { - type: DataTypes.INTEGER, + roleId: { allowNull: false, - validate: { - notNull: true - }, + onDelete: 'CASCADE', references: { - model: 'users', - key: 'id' + key: 'id', + model: 'roles' }, - onDelete: 'CASCADE' - }, - roleId: { type: DataTypes.INTEGER, - allowNull: false, validate: { notNull: true - }, + } + }, + userId: { + allowNull: false, + onDelete: 'CASCADE', references: { - model: 'roles', - key: 'id' + key: 'id', + model: 'users' }, - onDelete: 'CASCADE' + type: DataTypes.INTEGER, + validate: { + notNull: true + } } }); diff --git a/User/Models/Unverified.js b/User/Models/Unverified.js index c36c44e..5820078 100644 --- a/User/Models/Unverified.js +++ b/User/Models/Unverified.js @@ -1,37 +1,37 @@ export default (sequelize, DataTypes) => { const Unverified = sequelize.define('unverifieds', { - name: { - type: DataTypes.STRING, + email: { allowNull: false, - + onDelete: 'CASCADE', + references: { + key: 'email', + model: 'customers' + }, + type: DataTypes.STRING, + unique: 'email', validate: { + isEmail: true, notNull: true } }, - email: { - type: DataTypes.STRING, + name: { allowNull: false, - unique: 'email', + type: DataTypes.STRING, + validate: { - isEmail: true, notNull: true - }, - references: { - model: 'customers', - key: 'email' - }, - onDelete: 'CASCADE' + } }, password: { - type: DataTypes.STRING, allowNull: false, + type: DataTypes.STRING, validate: { notNull: true } }, token: { - type: DataTypes.TEXT, allowNull: false, + type: DataTypes.TEXT, validate: { notNull: true } diff --git a/User/Models/User.js b/User/Models/User.js index abd5c28..92005ba 100644 --- a/User/Models/User.js +++ b/User/Models/User.js @@ -1,63 +1,64 @@ import bcrypt from 'bcryptjs'; + import errorContstants from '#constants/error.js'; export default (sequelize, DataTypes) => { const User = sequelize.define( 'users', { - name: { - type: DataTypes.STRING, - allowNull: false, - - validate: { - notNull: true - } + active: { + defaultValue: 1, + type: DataTypes.BOOLEAN, + values: [0, 1] + }, + defaultProjectId: { + allowNull: true, + default: null, + type: DataTypes.INTEGER }, email: { - type: DataTypes.STRING, allowNull: false, + type: DataTypes.STRING, unique: true, validate: { isEmail: true, notNull: true } }, - password: { - type: DataTypes.STRING, + name: { allowNull: false, + type: DataTypes.STRING, + validate: { notNull: true - }, + } + }, + password: { + allowNull: false, set (value) { const hashedPass = bcrypt.hashSync(value, 8); this.setDataValue('password', hashedPass); + }, + type: DataTypes.STRING, + validate: { + notNull: true } }, profileImage: { - type: DataTypes.BOOLEAN, defaultValue: 0, - values: [0, 1] - }, - verifiedAt: { - type: DataTypes.DATE, - allowNull: true - }, - active: { type: DataTypes.BOOLEAN, - defaultValue: 1, values: [0, 1] }, - defaultProjectId: { - type: DataTypes.INTEGER, + verifiedAt: { allowNull: true, - default: null + type: DataTypes.DATE } }, { hooks: { - afterFind: function (model) { + afterFind: function afterFind (model) { if (!Array.isArray(model)) { if (!model.dataValues.active) throw new Error(errorContstants.ACCOUNT_INACTIVE); - // if(model.dataValues.verifiedAt) throw new Error(errorContstants.EMAIL_NOT_VERIFIED); + // If(model.dataValues.verifiedAt) throw new Error(errorContstants.EMAIL_NOT_VERIFIED); } } } diff --git a/User/Routes/authRoutes.js b/User/Routes/authRoutes.js index 556ad56..4386e31 100644 --- a/User/Routes/authRoutes.js +++ b/User/Routes/authRoutes.js @@ -1,7 +1,8 @@ import express from 'express'; -import { register, login, verifyCustomer, verifyUser, sendResetPasswordMail, resetPassword, refreshToken } from '../Controllers/authController.js'; -import { loginValidation, registerValidation, emailBodyValidation, tokenBodyValidation } from '../Validations/auth.js'; import { validate } from 'express-validation'; + +import { login, refreshToken, register, resetPassword, sendResetPasswordMail, verifyCustomer, verifyUser } from '../Controllers/authController.js'; +import { emailBodyValidation, loginValidation, registerValidation, tokenBodyValidation } from '../Validations/auth.js'; const Router = express.Router(); Router.post('/register', validate(registerValidation), register); diff --git a/User/Routes/passport.js b/User/Routes/passport.js index bb5412d..f1ffffe 100644 --- a/User/Routes/passport.js +++ b/User/Routes/passport.js @@ -1,5 +1,6 @@ import express from 'express'; import passport from 'passport'; + import {} from '#user/Service/passport.js'; const Router = express.Router(); diff --git a/User/Routes/roleRoutes.js b/User/Routes/roleRoutes.js index 31b2975..f20f584 100644 --- a/User/Routes/roleRoutes.js +++ b/User/Routes/roleRoutes.js @@ -1,6 +1,8 @@ import express from 'express'; -import { getAllRole, updateRole, saveRole, deleteRole, updateRolePermission, getUserRole, updateUserRole } from '../Controllers/roleController.js'; + import { validatePermission } from '#middlewares/permissions.js'; + +import { deleteRole, getAllRole, getUserRole, saveRole, updateRole, updateRolePermission, updateUserRole } from '../Controllers/roleController.js'; const Router = express.Router(); Router.get('/', validatePermission('Role', 'view'), getAllRole); diff --git a/User/Routes/superAdminRoutes.js b/User/Routes/superAdminRoutes.js index d771bd9..c2eeb13 100644 --- a/User/Routes/superAdminRoutes.js +++ b/User/Routes/superAdminRoutes.js @@ -1,7 +1,9 @@ import express from 'express'; -import { deleteCustomerByAdmin, syncTenant, getAllSession, terminateSession } from '../Controllers/superAdminController.js'; + import { validateSuperAdmin } from '#middlewares/permissions.js'; +import { deleteCustomerByAdmin, getAllSession, syncTenant, terminateSession } from '../Controllers/superAdminController.js'; + const Router = express.Router(); Router.use(validateSuperAdmin()); diff --git a/User/Routes/userRoutes.js b/User/Routes/userRoutes.js index 747994a..6ae5b96 100644 --- a/User/Routes/userRoutes.js +++ b/User/Routes/userRoutes.js @@ -1,22 +1,26 @@ import express from 'express'; +import { validate } from 'express-validation'; + +import { validateCustomerAdmin, validatePermission } from '#middlewares/permissions.js'; + import { addUser, - deleteUser, - changePassword, changeDetails, - getTeam, - resendVerificationEmail, + changePassword, deleteCustomerUser, - uploadProfileImage, + deleteUser, + getTeam, getUserDetailsByEmail, - logout - // toggleUserActiveInactive, - // myStatus, + logout, + resendVerificationEmail, + uploadProfileImage + /* + * ToggleUserActiveInactive, + * myStatus, + */ } from '../Controllers/userController.js'; import { emailBodyValidation, registerValidation } from '../Validations/auth.js'; -import { changePasswordValidation, changeDetailsValidation, activeInactiveValidation, userIdParamsValidation } from '../Validations/user.js'; -import { validate } from 'express-validation'; -import { validateCustomerAdmin, validatePermission } from '#middlewares/permissions.js'; +import { activeInactiveValidation, changeDetailsValidation, changePasswordValidation, userIdParamsValidation } from '../Validations/user.js'; const Router = express.Router(); diff --git a/User/Service/database.js b/User/Service/database.js index fdc8f9e..5bd4681 100644 --- a/User/Service/database.js +++ b/User/Service/database.js @@ -1,8 +1,9 @@ -import { deleteBucket } from '#storage/Service/awsService.js'; +import moment from 'moment'; + import errorContstants from '#constants/error.js'; -import db from '#utils/dataBaseConnection.js'; +import { deleteBucket } from '#storage/Service/awsService.js'; import cache from '#utils/cache.js'; -import moment from 'moment'; +import db from '#utils/dataBaseConnection.js'; const deleteCustomer = async (email) => { const tenantName = email.replace(/[^a-zA-Z0-9 ]/g, '').toLowerCase(); try { @@ -42,7 +43,7 @@ const syncDatabase = async (database, force = false, alter = false) => { if (model.name === 'customers' || model.name === 'unverifieds') continue; console.debug(`synced ${model.name} in ${database}`); synced.push(model.name); - await model.schema(database).sync({ force, alter }); + await model.schema(database).sync({ alter, force }); } await createSuperAdmin(); console.success('MODEL SYNC COMPLETED'); @@ -82,13 +83,13 @@ const createSuperAdmin = async () => { const Customer = db.customers; const User = db.users; await Customer.schema(process.env.DATABASE_PREFIX + process.env.DATABASE_NAME).create({ + admin: 2, email, - tenantName: process.env.DATABASE_NAME, - admin: 2 + tenantName: process.env.DATABASE_NAME }); await User.schema(process.env.DATABASE_PREFIX + process.env.DATABASE_NAME).create({ - name, email, + name, password, verifiedAt: moment() }); @@ -113,4 +114,4 @@ const dropDatabase = async (database) => { return false; } }; -export { deleteCustomer, syncDatabase, getAllTenant, getCachedKeys, createSuperAdmin, dropDatabase }; +export { createSuperAdmin, deleteCustomer, dropDatabase, getAllTenant, getCachedKeys, syncDatabase }; diff --git a/User/Service/passport.js b/User/Service/passport.js index b0df274..7bf2907 100644 --- a/User/Service/passport.js +++ b/User/Service/passport.js @@ -1,24 +1,25 @@ import passport from 'passport'; -// const { Strategy: FacebookStrategy } = require('passport-facebook'); +// Const { Strategy: FacebookStrategy } = require('passport-facebook'); import { Strategy as GitHubStrategy } from 'passport-github2'; import { OAuth2Strategy as GoogleStrategy } from 'passport-google-oauth'; -import { loginWithCredentals } from './user.js'; import { Strategy as LinkedInStrategy } from 'passport-linkedin-oauth2'; +import { loginWithCredentals } from './user.js'; + /** * Sign in with Google. */ if (process.env.GOOGLE_ID && process.env.GOOGLE_SECRET) { const googleStrategyConfig = new GoogleStrategy( { + callbackURL: '/auth/google/callback', clientID: process.env.GOOGLE_ID, clientSecret: process.env.GOOGLE_SECRET, - callbackURL: '/auth/google/callback', passReqToCallback: true }, async (req, accessToken, refreshToken, params, profile, done) => { try { - // const email = profile.emails.find((el) => el.verified)?.value; + // Const email = profile.emails.find((el) => el.verified)?.value; const email = profile.emails[0]?.value; const loggedInUser = await loginWithCredentals({ email, isPassRequired: false, rememberMe: true }); return done(null, loggedInUser); @@ -36,9 +37,9 @@ if (process.env.GOOGLE_ID && process.env.GOOGLE_SECRET) { if (process.env.GITHUB_ID && process.env.GITHUB_SECRET) { const githubStrategyConfig = new GitHubStrategy( { + callbackURL: '/auth/github/callback', clientID: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET, - callbackURL: '/auth/github/callback', passReqToCallback: true, scope: ['user:email'] }, @@ -62,11 +63,11 @@ if (process.env.LINKEDIN_ID && process.env.LINKEDIN_SECRET) { passport.use( new LinkedInStrategy( { + callbackURL: '/auth/linkedin/callback', clientID: process.env.LINKEDIN_ID, clientSecret: process.env.LINKEDIN_SECRET, - callbackURL: '/auth/linkedin/callback', - scope: ['profile'], - passReqToCallback: true + passReqToCallback: true, + scope: ['profile'] }, async (req, accessToken, refreshToken, profile, done) => { try { @@ -85,52 +86,54 @@ if (process.env.LINKEDIN_ID && process.env.LINKEDIN_SECRET) { /** * Sign in with Facebook. */ -// passport.use(new FacebookStrategy({ -// clientID: process.env.FACEBOOK_ID, -// clientSecret: process.env.FACEBOOK_SECRET, -// callbackURL: `${process.env.BASE_URL}/auth/facebook/callback`, -// profileFields: ['name', 'email', 'link', 'locale', 'timezone', 'gender'], -// passReqToCallback: true -// }, async (req, accessToken, refreshToken, profile, done) => { -// try { -// if (req.user) { -// const existingUser = await User.findOne({ facebook: profile.id }); -// if (existingUser) { -// req.flash('errors', { msg: 'There is already a Facebook account that belongs to you. Sign in with that account or delete it, then link it with your current account.' }); -// return done(null, existingUser); -// } -// const user = await User.findById(req.user.id); -// user.facebook = profile.id; -// user.tokens.push({ kind: 'facebook', accessToken }); -// user.profile.name = user.profile.name || `${profile.name.givenName} ${profile.name.familyName}`; -// user.profile.gender = user.profile.gender || profile._json.gender; -// user.profile.picture = user.profile.picture || `https://graph.facebook.com/${profile.id}/picture?type=large`; -// await user.save(); -// req.flash('info', { msg: 'Facebook account has been linked.' }); -// return done(null, user); -// } -// const existingUser = await User.findOne({ facebook: profile.id }); -// if (existingUser) { -// return done(null, existingUser); -// } -// const existingEmailUser = await User.findOne({ email: profile._json.email }); -// if (existingEmailUser) { -// req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with Facebook manually from Account Settings.' }); -// return done(null, existingEmailUser); -// } -// const user = new User(); -// user.email = profile._json.email; -// user.facebook = profile.id; -// user.tokens.push({ kind: 'facebook', accessToken }); -// user.profile.name = `${profile.name.givenName} ${profile.name.familyName}`; -// user.profile.gender = profile._json.gender; -// user.profile.picture = `https://graph.facebook.com/${profile.id}/picture?type=large`; -// user.profile.location = profile._json.location ? profile._json.location.name : ''; -// await user.save(); -// return done(null, user); -// } catch (err) { -// return done(err); -// } -// })); +/* + * Passport.use(new FacebookStrategy({ + * clientID: process.env.FACEBOOK_ID, + * clientSecret: process.env.FACEBOOK_SECRET, + * callbackURL: `${process.env.BASE_URL}/auth/facebook/callback`, + * profileFields: ['name', 'email', 'link', 'locale', 'timezone', 'gender'], + * passReqToCallback: true + * }, async (req, accessToken, refreshToken, profile, done) => { + * try { + * if (req.user) { + * const existingUser = await User.findOne({ facebook: profile.id }); + * if (existingUser) { + * req.flash('errors', { msg: 'There is already a Facebook account that belongs to you. Sign in with that account or delete it, then link it with your current account.' }); + * return done(null, existingUser); + * } + * const user = await User.findById(req.user.id); + * user.facebook = profile.id; + * user.tokens.push({ kind: 'facebook', accessToken }); + * user.profile.name = user.profile.name || `${profile.name.givenName} ${profile.name.familyName}`; + * user.profile.gender = user.profile.gender || profile._json.gender; + * user.profile.picture = user.profile.picture || `https://graph.facebook.com/${profile.id}/picture?type=large`; + * await user.save(); + * req.flash('info', { msg: 'Facebook account has been linked.' }); + * return done(null, user); + * } + * const existingUser = await User.findOne({ facebook: profile.id }); + * if (existingUser) { + * return done(null, existingUser); + * } + * const existingEmailUser = await User.findOne({ email: profile._json.email }); + * if (existingEmailUser) { + * req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with Facebook manually from Account Settings.' }); + * return done(null, existingEmailUser); + * } + * const user = new User(); + * user.email = profile._json.email; + * user.facebook = profile.id; + * user.tokens.push({ kind: 'facebook', accessToken }); + * user.profile.name = `${profile.name.givenName} ${profile.name.familyName}`; + * user.profile.gender = profile._json.gender; + * user.profile.picture = `https://graph.facebook.com/${profile.id}/picture?type=large`; + * user.profile.location = profile._json.location ? profile._json.location.name : ''; + * await user.save(); + * return done(null, user); + * } catch (err) { + * return done(err); + * } + * })); + */ export default {}; diff --git a/User/Service/user.js b/User/Service/user.js index 425d08e..f94a6d9 100644 --- a/User/Service/user.js +++ b/User/Service/user.js @@ -1,8 +1,9 @@ -import db from '#utils/dataBaseConnection.js'; import bcrypt from 'bcryptjs'; -import { createToken } from '#utils/jwt.js'; -import cache from '#utils/cache.js'; + import errorContstants from '#constants/error.js'; +import cache from '#utils/cache.js'; +import db from '#utils/dataBaseConnection.js'; +import { createToken } from '#utils/jwt.js'; // Main const Customer = db.customers; @@ -23,25 +24,25 @@ const loginWithCredentals = async ({ email, password, rememberMe, isPassRequired const tenant = process.env.DATABASE_PREFIX + customer.tenantName; const user = await User.schema(tenant).findOne({ - where: { email }, include: [ { - model: UserRole.schema(tenant), attributes: ['roleId'], include: [ { - model: Role.schema(tenant), attributes: ['name'], include: [ { - model: Permission.schema(tenant), - attributes: ['name', 'view', 'add', 'edit', 'delete'] + attributes: ['name', 'view', 'add', 'edit', 'delete'], + model: Permission.schema(tenant) } - ] + ], + model: Role.schema(tenant) } - ] + ], + model: UserRole.schema(tenant) } - ] + ], + where: { email } }); if (!user) throw new Error(errorContstants.RECORD_NOT_FOUND); @@ -63,9 +64,9 @@ const loginWithCredentals = async ({ email, password, rememberMe, isPassRequired const superAdmin = customer.admin === 2; const customerAdmin = customer.admin || superAdmin; - const tokenData = { id, email, tenant: customer.tenantName }; + const tokenData = { email, id, tenant: customer.tenantName }; const accessToken = createToken( - { ...tokenData, customerAdmin, superAdmin, permissions: allPermissions }, + { ...tokenData, customerAdmin, permissions: allPermissions, superAdmin }, process.env.JWT_ACCESS_SECRET, rememberMe ? process.env.JWT_ACCESS_REMEMBER_EXPIRATION : process.env.JWT_ACCESS_EXPIRATION ); diff --git a/User/Validations/auth.js b/User/Validations/auth.js index a9f4390..2884e6d 100644 --- a/User/Validations/auth.js +++ b/User/Validations/auth.js @@ -8,8 +8,8 @@ const loginValidation = { }; const registerValidation = { body: Joi.object({ - name: Joi.string().min(3).max(100).required(), email: Joi.string().min(5).required().email(), + name: Joi.string().min(3).max(100).required(), password: Joi.string().min(8).max(15).required() }) }; @@ -25,4 +25,4 @@ const tokenBodyValidation = { token: Joi.string().required() }) }; -export { loginValidation, registerValidation, emailBodyValidation, tokenBodyValidation }; +export { emailBodyValidation, loginValidation, registerValidation, tokenBodyValidation }; diff --git a/User/Validations/role.js b/User/Validations/role.js index c886483..c197063 100644 --- a/User/Validations/role.js +++ b/User/Validations/role.js @@ -5,11 +5,11 @@ const updateNameValidation = joi.object({ roleId: joi.number().integer().required() }); const updatePermissionValidation = joi.object({ - name: joi.string().min(3).max(100).required(), add: joi.boolean().required(), + delete: joi.boolean().required(), edit: joi.boolean().required(), - view: joi.boolean().required(), - delete: joi.boolean().required() + name: joi.string().min(3).max(100).required(), + view: joi.boolean().required() }); export { updateNameValidation, updatePermissionValidation }; diff --git a/User/Validations/user.js b/User/Validations/user.js index 2d2123c..fd5ed86 100644 --- a/User/Validations/user.js +++ b/User/Validations/user.js @@ -2,15 +2,15 @@ import { Joi } from 'express-validation'; const changePasswordValidation = { body: Joi.object({ - oldPassword: Joi.string().min(8).max(15).required(), - newPassword: Joi.string().min(8).max(15).required() + newPassword: Joi.string().min(8).max(15).required(), + oldPassword: Joi.string().min(8).max(15).required() }) }; const changeDetailsValidation = { body: Joi.object({ - name: Joi.string().max(100), - defaultProjectId: Joi.number().integer() + defaultProjectId: Joi.number().integer(), + name: Joi.string().max(100) }) }; @@ -25,4 +25,4 @@ const userIdParamsValidation = { params: Joi.object({ userId: Joi.number().integer().required() }) }; -export { changePasswordValidation, changeDetailsValidation, activeInactiveValidation, userIdParamsValidation }; +export { activeInactiveValidation, changeDetailsValidation, changePasswordValidation, userIdParamsValidation }; diff --git a/Utils/Constants/actionEventOptions.js b/Utils/Constants/actionEventOptions.js index 4ebaf5b..96ac0ee 100644 --- a/Utils/Constants/actionEventOptions.js +++ b/Utils/Constants/actionEventOptions.js @@ -1,6 +1,6 @@ export const KeyboardButtonList = [ 'NULL', - 'CANCEL', // ^break + 'CANCEL', 'HELP', 'BACK_SPACE', 'TAB', @@ -30,7 +30,8 @@ export const KeyboardButtonList = [ 'SEMICOLON', 'EQUALS', - 'NUMPAD0', // number pad keys + // Number pad keys + 'NUMPAD0', 'NUMPAD1', 'NUMPAD2', 'NUMPAD3', @@ -47,7 +48,8 @@ export const KeyboardButtonList = [ 'DECIMAL', 'DIVIDE', - 'F1', // function keys + // Function keys + 'F1', 'F2', 'F3', 'F4', @@ -60,8 +62,11 @@ export const KeyboardButtonList = [ 'F11', 'F12', - 'COMMAND', // Apple command key - 'META' // alias for Windows key + // Apple command key + 'COMMAND', + + // Alias for Windows key + 'META' ]; export const IfType = ['Boolean', 'Number', 'String']; diff --git a/Utils/Constants/actionEvents.js b/Utils/Constants/actionEvents.js index 2a8186e..75fd511 100644 --- a/Utils/Constants/actionEvents.js +++ b/Utils/Constants/actionEvents.js @@ -1,4 +1,4 @@ -import { KeyboardButtonList, IfType, ConditionList, ConvertList, WaitUntil, RandomType } from './actionEventOptions.js'; +import { ConditionList, ConvertList, IfType, KeyboardButtonList, RandomType, WaitUntil } from './actionEventOptions.js'; export const actionEvents = [ { @@ -9,22 +9,22 @@ export const actionEvents = [ { name: 'Click', object: true, - testParameters: [{ name: 'Timeout', defaultValue: '1000' }] + testParameters: [{ defaultValue: '1000', name: 'Timeout' }] }, { name: 'Double Click', object: true, - testParameters: [{ name: 'Timeout', defaultValue: '1000' }] + testParameters: [{ defaultValue: '1000', name: 'Timeout' }] }, { name: 'Right Click', object: true, - testParameters: [{ name: 'Timeout', defaultValue: '1000' }] + testParameters: [{ defaultValue: '1000', name: 'Timeout' }] }, { name: 'Enter Text', object: true, - testParameters: [{ name: 'Text' }, { name: 'Timeout', defaultValue: '1000' }] + testParameters: [{ name: 'Text' }, { defaultValue: '1000', name: 'Timeout' }] }, { name: 'Enter Date Time', @@ -34,7 +34,7 @@ export const actionEvents = [ { name: 'Clear Input', object: true, - testParameters: [{ name: 'Timeout', defaultValue: '1000' }] + testParameters: [{ defaultValue: '1000', name: 'Timeout' }] }, { name: 'Press Button', @@ -76,7 +76,7 @@ export const actionEvents = [ object: true, testParameters: [ { name: 'WaitType', options: WaitUntil }, - { name: 'Timeout', defaultValue: '1000' } + { defaultValue: '1000', name: 'Timeout' } ] }, { @@ -167,17 +167,17 @@ export const actionEvents = [ { name: 'Click By Javascript', object: true, - testParameters: [{ name: 'Timeout', defaultValue: '1000' }] + testParameters: [{ defaultValue: '1000', name: 'Timeout' }] }, { name: 'Click Link By Text', object: false, - testParameters: [{ name: 'Text' }, { name: 'Timeout', defaultValue: '1000' }] + testParameters: [{ name: 'Text' }, { defaultValue: '1000', name: 'Timeout' }] }, { name: 'Click Link By Partial Text', object: false, - testParameters: [{ name: 'Text' }, { name: 'Timeout', defaultValue: '1000' }] + testParameters: [{ name: 'Text' }, { defaultValue: '1000', name: 'Timeout' }] }, { name: 'Hover Mouse', @@ -352,6 +352,6 @@ export const actionEvents = [ { name: 'Wait For Network Calls', object: false, - testParameters: [{ name: 'Count' }, { name: 'Timeout', defaultValue: '1000' }] + testParameters: [{ name: 'Count' }, { defaultValue: '1000', name: 'Timeout' }] } ]; diff --git a/Utils/Constants/error.js b/Utils/Constants/error.js index 134a137..02d4f2c 100644 --- a/Utils/Constants/error.js +++ b/Utils/Constants/error.js @@ -1,23 +1,23 @@ const errorContstants = { - UNAUTHORIZED: 'Unauthorized!', + ACCESS_TOKEN_NOT_FOUND: 'Access Token Not Found', ACCOUNT_BLOCKED: 'Account Blocked!', ACCOUNT_INACTIVE: 'Account Inactive!', - INCORRECT_PASSWORD: 'Incorrect Password!', - INVALID_PERMISSION: 'Invalid Permission!', + CUSTOMER_DATABASE_ALREADY_EXIST: 'Customer Database Already Exists', + EMAIL_ALREADY_VERIFIED: 'Email Already Verified', + EMAIL_NOT_VERIFIED: 'Email Not Verified', ENDPOINT_NOT_FOUND: 'Endpoint Not Found!', - RECORD_NOT_FOUND: 'Record Not Found!', - INVALID_FILE: 'Invalid File', + INCORRECT_PASSWORD: 'Incorrect Password!', INVALID_BUCKET: 'Invalid Bucket', + INVALID_FILE: 'Invalid File', INVALID_FOLDER: 'Invalid Folder', - EMAIL_ALREADY_VERIFIED: 'Email Already Verified', - EMAIL_NOT_VERIFIED: 'Email Not Verified', + INVALID_PERMISSION: 'Invalid Permission!', + NOT_AN_ACTIVE_SESSION: 'Not An Active Session!', + RECORD_NOT_FOUND: 'Record Not Found!', REFRESH_TOKEN_NOT_FOUND: 'Refresh Token Not Found', - ACCESS_TOKEN_NOT_FOUND: 'Access Token Not Found', SOMETHING_WENT_WRONG: 'Something Went Wrong!', TIMEOUT: 'Timeout!', - NOT_AN_ACTIVE_SESSION: 'Not An Active Session!', UNABLE_TO_DELETE_MASTER_DATABASE: 'Unable To Delete Master Database!', - UNAUTHORIZED_ORIGIN: 'Unauthorized Origin', - CUSTOMER_DATABASE_ALREADY_EXIST: 'Customer Database Already Exists' + UNAUTHORIZED: 'Unauthorized!', + UNAUTHORIZED_ORIGIN: 'Unauthorized Origin' }; export default errorContstants; diff --git a/Utils/Constants/success.js b/Utils/Constants/success.js index b28a30b..65b0e5d 100644 --- a/Utils/Constants/success.js +++ b/Utils/Constants/success.js @@ -1,7 +1,7 @@ const successContstants = { DELETED: 'Deleted Succesfully!', - UPDATED: 'Updated Succesfully!', EMAIL_VERIFICATION_SUCCESSFULL: 'Email Verified successfull', - PASSWORD_RESET_SUCCESSFULL: 'Passwors Reset successfull' + PASSWORD_RESET_SUCCESSFULL: 'Passwors Reset successfull', + UPDATED: 'Updated Succesfully!' }; export default successContstants; diff --git a/Utils/Logger/api.js b/Utils/Logger/api.js new file mode 100644 index 0000000..c1420c4 --- /dev/null +++ b/Utils/Logger/api.js @@ -0,0 +1,15 @@ +import morganBody from 'morgan-body'; + +const morgalApiLogger = (app) => { + if (process.env.PRINT_API_REQ_RES === 'false') return console.log('API logger is turned OFF'); + console.log('API logger is turned ON'); + return morganBody(app, { + includeNewLine: true, + logReqHeaderList: ['x-project-id'], + prettify: false, + skip: (req) => req.url.includes('management') || req.url.includes('favicon') || req.method === 'OPTIONS', + timezone: 'Asia/Kolkata' + }); +}; + +export default morgalApiLogger; diff --git a/Utils/Logger/console.js b/Utils/Logger/console.js new file mode 100644 index 0000000..a495269 --- /dev/null +++ b/Utils/Logger/console.js @@ -0,0 +1,102 @@ +import chalk from 'chalk'; + +const overrideInfo = () => { + if (process.env.PRINT_CONSOLE_INFO === 'false') { + console.log = () => { + // Do nothing. + }; + } + + const { log } = console; + console.log = (...e) => { + try { + throw new Error(); + } catch (error) { + const fileName = getFileNameFromError(error); + log.apply(console, ['\n', `[${new Date().toLocaleString()}]`, chalk.blue('INFO:'), fileName, ...e]); + } + }; +}; + +const overrideWarn = () => { + if (process.env.PRINT_CONSOLE_WARN === 'false') { + console.log = () => { + // Do nothing. + }; + } + const log = console.warn; + try { + throw new Error(); + } catch (error) { + console.warn = (...e) => { + const fileName = getFileNameFromError(error); + log.apply(console, ['\n', `[${new Date().toLocaleString()}]`, chalk.yellow('WARN:'), fileName, ...e]); + }; + } +}; + +const overrideError = () => { + if (process.env.PRINT_CONSOLE_ERROR === 'false') { + console.log = () => { + // Do nothing. + }; + } + const log = console.error; + console.error = (...e) => { + try { + throw new Error(); + } catch (error) { + const fileName = getFileNameFromError(error); + log.apply(console, ['\n', `[${new Date().toLocaleString()}]`, chalk.red('ERROR:'), fileName, ...e]); + } + }; +}; + +const overrideDebug = () => { + if (process.env.PRINT_CONSOLE_DEBUG === 'false') { + console.log = () => { + // Do nothing. + }; + } + + const log = console.debug; + console.debug = (...e) => { + try { + throw new Error(); + } catch (error) { + const fileName = getFileNameFromError(error); + log.apply(console, ['\n', `[${new Date().toLocaleString()}]`, chalk.magenta('DEBUG:'), fileName, ...e]); + } + }; +}; + +const overrideSuccess = () => { + if (process.env.PRINT_CONSOLE_SUCCESS === 'false') { + console.log = () => { + // Do nothing. + }; + } + + const log = console.info; + + console.success = (...e) => { + try { + throw new Error(); + } catch (error) { + const fileName = getFileNameFromError(error); + log.apply(console, ['\n', `[${new Date().toLocaleString()}]`, chalk.green('SUCCESS:'), fileName, ...e]); + } + }; +}; + +const overrideConsole = () => { + overrideInfo(); + overrideWarn(); + overrideError(); + overrideSuccess(); + overrideDebug(); +}; + +export default overrideConsole; + +const getFileNameFromError = (error) => `[${error.stack.split('\n')[2].split('/').at(-1).replace(/\)/, '')}]`; diff --git a/Utils/Mail/HTML/register.js b/Utils/Mail/HTML/register.js index 1d249ed..a3407c2 100644 --- a/Utils/Mail/HTML/register.js +++ b/Utils/Mail/HTML/register.js @@ -1,5 +1,4 @@ -const registerHTML = (name, link) => { - return ` +const registerHTML = (name, link) => `
Hi ${name}, We're excited to have you get started. First, you need to confirm your account.
@@ -9,5 +8,4 @@ const registerHTML = (name, link) => { ${link} `; -}; export default registerHTML; diff --git a/Utils/Mail/HTML/resetPassword.js b/Utils/Mail/HTML/resetPassword.js index 41e556a..d7403e6 100644 --- a/Utils/Mail/HTML/resetPassword.js +++ b/Utils/Mail/HTML/resetPassword.js @@ -1,5 +1,4 @@ -const resetPasswordHtml = (name, link) => { - return ` +const resetPasswordHtml = (name, link) => `Hi ${name}, As per your request, we have sent you a link to rest your password.
@@ -9,5 +8,4 @@ const resetPasswordHtml = (name, link) => { ${link} `; -}; export default resetPasswordHtml; diff --git a/Utils/Mail/nodeMailer.js b/Utils/Mail/nodeMailer.js index b5b7109..ea4abb7 100644 --- a/Utils/Mail/nodeMailer.js +++ b/Utils/Mail/nodeMailer.js @@ -1,33 +1,34 @@ import nodemailer from 'nodemailer'; + import { createToken } from '#utils/jwt.js'; import registerHTML from '#utils/Mail/HTML/register.js'; import resetPasswordHtml from '#utils/Mail/HTML/resetPassword.js'; const transporter = nodemailer.createTransport({ - service: process.env.MAILER_SERVICE, auth: { - user: process.env.MAILER_USER, - pass: process.env.MAILER_PASS - } + pass: process.env.MAILER_PASS, + user: process.env.MAILER_USER + }, + service: process.env.MAILER_SERVICE }); const sendMailApi = (req, res) => { - /* #swagger.tags = ["Mail"] - #swagger.security = [{"apiKeyAuth": []}] - */ - transporter.sendMail(req.body, function (error, info) { + /* + * #swagger.tags = ["Mail"] + * #swagger.security = [{"apiKeyAuth": []}] + */ + transporter.sendMail(req.body, (error, info) => { if (error) { return res.status(400).json({ error }); - } else { - return res.status(200).json(info); } + return res.status(200).json(info); }); }; -const sendMail = async (data, type) => { +const sendMail = (data, type) => { let mailOption = { - to: '', + html: '', subject: '', text: '', - html: '' + to: '' }; let token = ''; let link = ''; @@ -36,18 +37,18 @@ const sendMail = async (data, type) => { token = createToken({ email: data.email }, process.env.JWT_VERIFICATION_SECRET); link = `${process.env.WEBSITE_HOME}/auth/verify-customer/${token}`; mailOption = { - to: data.email, + html: registerHTML(data.name, link), subject: 'Customer Registration Successfull', - html: registerHTML(data.name, link) + to: data.email }; break; case 'addUser': token = createToken({ email: data.email, tenant: data.tenant }, process.env.JWT_VERIFICATION_SECRET); link = `${process.env.WEBSITE_HOME}/auth/verify-user/${token}`; mailOption = { - to: data.email, + html: registerHTML(data.name, link), subject: 'Registration Successfull', - html: registerHTML(data.name, link) + to: data.email }; console.log(link); break; @@ -55,13 +56,15 @@ const sendMail = async (data, type) => { token = createToken({ email: data.email, tenant: data.tenant }, process.env.JWT_RESET_SECRET, process.env.JWT_RESET_EXPIRATION); link = `${process.env.WEBSITE_HOME}/reset-password/${token}`; mailOption = { - to: data.email, + html: resetPasswordHtml(data.name, link), subject: 'Password Reset', - html: resetPasswordHtml(data.name, link) + to: data.email }; break; + default: + break; } - transporter.sendMail({ ...mailOption, from: process.env.MAILER_FROM }, function (error, info) { + transporter.sendMail({ ...mailOption, from: process.env.MAILER_FROM }, (error, info) => { if (error) { console.log(error); console.log('Failed to send email'); @@ -71,4 +74,4 @@ const sendMail = async (data, type) => { } }); }; -export { sendMailApi, sendMail }; +export { sendMail, sendMailApi }; diff --git a/Utils/Middlewares/default.js b/Utils/Middlewares/default.js index a4ca3f2..95ab1d4 100644 --- a/Utils/Middlewares/default.js +++ b/Utils/Middlewares/default.js @@ -1,14 +1,16 @@ -// import { extractToken } from "../jwt.js"; -// import getError from "../sequelizeError.js"; -// import errorContstants from "#constants/error.js"; -// import pkg from "jsonwebtoken"; +/* + * Import { extractToken } from "../jwt.js"; + * import getError from "../sequelizeError.js"; + * import errorContstants from "#constants/error.js"; + * import pkg from "jsonwebtoken"; + */ -export const defaultMiddleware = () => { - return async (req, res, next) => { - req.user = { - tenant: 'master', - database: process.env.DATABASE_NAME - }; - next(); +const defaultMiddleware = () => (req, res, next) => { + req.user = { + database: process.env.DATABASE_NAME, + tenant: 'master' }; + next(); }; + +export default defaultMiddleware; diff --git a/Utils/Middlewares/jwt.js b/Utils/Middlewares/jwt.js index e1b3506..e2d1a01 100644 --- a/Utils/Middlewares/jwt.js +++ b/Utils/Middlewares/jwt.js @@ -1,30 +1,29 @@ -import { extractToken } from '#utils/jwt.js'; -import getError from '#utils/error.js'; -import errorContstants from '#constants/error.js'; import pkg from 'jsonwebtoken'; + +import errorContstants from '#constants/error.js'; import cache from '#utils/cache.js'; +import getError from '#utils/error.js'; +import { extractToken } from '#utils/jwt.js'; const { verify } = pkg; -export const validateToken = () => { - return async (req, res, next) => { - try { - const token = extractToken(req); - if (!token) return res.status(401).json({ error: errorContstants.ACCESS_TOKEN_NOT_FOUND }); - const data = verify(token, process.env.JWT_ACCESS_SECRET); - if (data) { - const tokenCheck = handleCachedTokenCheck(data.email, data.tenant, token); - if (!tokenCheck) return res.status(401).json({ error: errorContstants.NOT_AN_ACTIVE_SESSION }); +export const validateToken = () => (req, res, next) => { + try { + const token = extractToken(req); + if (!token) return res.status(401).json({ error: errorContstants.ACCESS_TOKEN_NOT_FOUND }); + const data = verify(token, process.env.JWT_ACCESS_SECRET); + if (data) { + const tokenCheck = handleCachedTokenCheck(data.email, data.tenant, token); + if (!tokenCheck) return res.status(401).json({ error: errorContstants.NOT_AN_ACTIVE_SESSION }); - const temp = { ...data }; - delete temp.iat; - delete temp.exp; - req.user = temp; - req.database = process.env.DATABASE_PREFIX + temp.tenant; - next(); - } - } catch (e) { - getError(e, res, 'Access'); + const temp = { ...data }; + delete temp.iat; + delete temp.exp; + req.user = temp; + req.database = process.env.DATABASE_PREFIX + temp.tenant; + next(); } - }; + } catch (e) { + getError(e, res, 'Access'); + } }; const handleCachedTokenCheck = (email, tenant, token) => { diff --git a/Utils/Middlewares/permissions.js b/Utils/Middlewares/permissions.js index ce051c2..a17f696 100644 --- a/Utils/Middlewares/permissions.js +++ b/Utils/Middlewares/permissions.js @@ -1,63 +1,53 @@ import errorContstants from '#constants/error.js'; -import getError from '#utils/error.js'; import db from '#utils/dataBaseConnection.js'; +import getError from '#utils/error.js'; import { idValidation } from '#validations/index.js'; const UserProject = db.userProjects; -const validatePermission = (permissionName, method) => { - return async (req, res, next) => { - try { - if (!req.user.customerAdmin) { - const allowed = await req.user.permissions.some((permission) => { - return permissionName === permission.name && permission[method] === true; - }); - if (!allowed) return res.status(401).json({ error: errorContstants.UNAUTHORIZED }); - } - next(); - } catch (e) { - return getError(e, res); +const validatePermission = (permissionName, method) => async (req, res, next) => { + try { + if (!req.user.customerAdmin) { + const allowed = await req.user.permissions.some((permission) => permissionName === permission.name && permission[method] === true); + if (!allowed) return res.status(401).json({ error: errorContstants.UNAUTHORIZED }); } - }; + return next(); + } catch (e) { + return getError(e, res); + } }; -const validateSuperAdmin = () => { - return async (req, res, next) => { - try { - if (!req.user.superAdmin) return res.status(401).json({ error: errorContstants.UNAUTHORIZED }); - next(); - } catch (e) { - return getError(e, res); - } - }; +const validateSuperAdmin = () => (req, res, next) => { + try { + if (!req.user.superAdmin) return res.status(401).json({ error: errorContstants.UNAUTHORIZED }); + return next(); + } catch (e) { + return getError(e, res); + } }; -const validateCustomerAdmin = () => { - return async (req, res, next) => { - try { - if (!req.user.customerAdmin) return res.status(401).json({ error: errorContstants.UNAUTHORIZED }); - next(); - } catch (e) { - return getError(e, res); - } - }; +const validateCustomerAdmin = () => (req, res, next) => { + try { + if (!req.user.customerAdmin) return res.status(401).json({ error: errorContstants.UNAUTHORIZED }); + return next(); + } catch (e) { + return getError(e, res); + } }; -const validateUserProject = () => { - return async (req, res, next) => { - try { - const projectId = req.params.projectId || req.headers['x-project-id']; - const { error } = idValidation.validate({ id: projectId }); - if (error) throw new Error(error.details[0].message); +const validateUserProject = () => async (req, res, next) => { + try { + const projectId = req.params.projectId || req.headers['x-project-id']; + const { error } = idValidation.validate({ id: projectId }); + if (error) throw new Error(error.details[0].message); - const userProject = await UserProject.schema(req.database).findOne({ - where: { userId: req.user.id, projectId } - }); - if (!userProject) return res.status(401).json({ error: errorContstants.UNAUTHORIZED }); + const userProject = await UserProject.schema(req.database).findOne({ + where: { projectId, userId: req.user.id } + }); + if (!userProject) return res.status(401).json({ error: errorContstants.UNAUTHORIZED }); - next(); - } catch (e) { - return getError(e, res); - } - }; + return next(); + } catch (e) { + return getError(e, res); + } }; -export { validatePermission, validateSuperAdmin, validateCustomerAdmin, validateUserProject }; +export { validateCustomerAdmin, validatePermission, validateSuperAdmin, validateUserProject }; diff --git a/Utils/Middlewares/server.js b/Utils/Middlewares/server.js index 454cabd..fdef0d3 100644 --- a/Utils/Middlewares/server.js +++ b/Utils/Middlewares/server.js @@ -1,13 +1,14 @@ -import { rateLimit } from 'express-rate-limit'; -import { encryptWithAES } from '#encryption/Service/aes.service.js'; import cors from 'cors'; -import errorContstants from '#constants/error.js'; +import { rateLimit } from 'express-rate-limit'; import { ValidationError } from 'express-validation'; -function setupTimeout (app) { + +import errorContstants from '#constants/error.js'; +import { encryptWithAES } from '#encryption/Service/aes.service.js'; +const setupTimeout = (app) => { if (!process.env.TIMEOUT) return console.log('Timeout is turned OFF'); console.log(`Timeout is turned ON with ${process.env.TIMEOUT}`); - app.use(function (req, res, next) { - res.setTimeout(parseInt(process.env.TIMEOUT) || 60_000, function () { + app.use((req, res, next) => { + res.setTimeout(parseInt(process.env.TIMEOUT) || 60_000, () => { console.error('Request has timed out.', req); res.status(408).json({ error: errorContstants.TIMEOUT }); res.json = @@ -16,70 +17,81 @@ function setupTimeout (app) { res.jsonP = res.end = res.sendStatus = - function () { + function sendStatus () { return this; }; }); next(); }); -} +}; -function setupRateLimiter (app) { +const setupRateLimiter = (app) => { if (!process.env.RATE_LIMIT_WINDOW || !process.env.RATE_LIMIT) return console.log('Rate Limiter is turned OFF'); app.set('trust proxy', true); console.log(`Rate Limiter is turned ON with ${process.env.RATE_LIMIT_WINDOW}:${process.env.RATE_LIMIT}`); const limiter = rateLimit({ - windowMs: process.env.RATE_LIMIT_WINDOW, // 10 minutes - limit: process.env.RATE_LIMIT, // Limit each IP to 100 requests per `window` (here, per 10 minutes). - standardHeaders: 'draft-7', // draft-6: `RateLimit-*` headers; draft-7: combined `RateLimit` header - legacyHeaders: false, // Disable the `X-RateLimit-*` headers. - message: { error: 'Too many requests, please try again later.', limitWindow: process.env.RATE_LIMIT_WINDOW + 's', limit: process.env.RATE_LIMIT } - // store: ... , // Use an external store for consistency across multiple server instances. - // skip: (req) => req.url === '/reset', + + // Draft-6: `RateLimit-*` headers; draft-7: combined `RateLimit` header + legacyHeaders: false, + + // 10 minutes + limit: process.env.RATE_LIMIT, + + // Disable the `X-RateLimit-*` headers. + message: { error: 'Too many requests, please try again later.', limit: process.env.RATE_LIMIT, limitWindow: `${process.env.RATE_LIMIT_WINDOW}s` }, + + // Limit each IP to 100 requests per `window` (here, per 10 minutes). + standardHeaders: 'draft-7', + + windowMs: process.env.RATE_LIMIT_WINDOW + /* + * Store: ... , // Use an external store for consistency across multiple server instances. + * skip: (req) => req.url === '/reset', + */ }); app.use(limiter); -} +}; -function setupCors (app) { +const setupCors = (app) => { const whitelist = process.env.CORS.split(','); - // var whitelist = ['http://localhost:8000', 'http://localhost:8080']; //white list consumers + // Var whitelist = ['http://localhost:8000', 'http://localhost:8080']; //white list consumers const corsOptions = { - origin: function (origin, callback) { - if (whitelist.indexOf(origin) !== -1 || !process.env.CORS) { + allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'device-remember-token', 'Access-Control-Allow-Origin', 'Origin', 'Accept', 'x-project-id"'], + methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'], + origin: function origin (og, callback) { + if (whitelist.indexOf(og) !== -1 || !process.env.CORS) { callback(null, true); } else { callback(new Error('Not allowed by CORS')); } - }, - methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'], - allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'device-remember-token', 'Access-Control-Allow-Origin', 'Origin', 'Accept', 'x-project-id"'] + } }; app.use(cors(corsOptions)); -} +}; -function setupResponseInterceptor (app) { +const setupResponseInterceptor = (app) => { console.log('Response Interceptor is Turned ON'); - app.use(function (req, res, next) { + app.use((req, res, next) => { const originalSend = res.send; - res.send = function () { - const errorObj = arguments[0]; + res.send = function send (...args) { + const errorObj = args[0]; if (typeof errorObj === 'object' && errorObj.error) { errorObj.method = req.method; errorObj.path = req.url; errorObj.status = res.statusCode; - arguments[0] = JSON.stringify(errorObj); + args[0] = JSON.stringify(errorObj); } - if (process.env.ENCRYPTION === 'true' && !(req.url.includes('decrypt') || req.url.includes('encrypt'))) arguments[0] = JSON.stringify(encryptWithAES(arguments[0])); - // console.log(result) - originalSend.apply(res, arguments); + if (process.env.ENCRYPTION === 'true' && !(req.url.includes('decrypt') || req.url.includes('encrypt'))) args[0] = JSON.stringify(encryptWithAES(args[0])); + // Console.log(result) + originalSend.apply(res, args); }; next(); }); -} +}; -function setupErrorInterceptor (app) { +const setupErrorInterceptor = (app) => { console.log('ERROR Interceptor is Turned ON'); app.use((err, req, res, next) => { const errorObj = getErrorObj(req, res); @@ -96,10 +108,10 @@ function setupErrorInterceptor (app) { } next(err); }); -} +}; -function setupValidationErrorInterceptor (app) { - app.use(function (err, req, res, next) { +const setupValidationErrorInterceptor = (app) => { + app.use((err, req, res, next) => { const errorObj = getErrorObj(req, res); if (err instanceof ValidationError) { const error = err.details.body?.[0].message || err.details.params?.[0].message || err.details.query?.[0].message || err.details.headers?.[0].message; @@ -107,14 +119,12 @@ function setupValidationErrorInterceptor (app) { } next(err); }); -} +}; -function getErrorObj (req, res) { - return { - method: req.method, - path: req.url, - status: res.statusCode - }; -} +const getErrorObj = (req, res) => ({ + method: req.method, + path: req.url, + status: res.statusCode +}); -export { setupTimeout, setupRateLimiter, setupCors, setupResponseInterceptor, setupErrorInterceptor, setupValidationErrorInterceptor }; +export { setupCors, setupErrorInterceptor, setupRateLimiter, setupResponseInterceptor, setupTimeout, setupValidationErrorInterceptor }; diff --git a/Utils/Validations/index.js b/Utils/Validations/index.js index 3be3531..fcd7888 100644 --- a/Utils/Validations/index.js +++ b/Utils/Validations/index.js @@ -8,10 +8,10 @@ export const idValidation = joi.object({ }); export const nameDesTagPrjValidation = joi.object({ - name: joi.string().min(3).max(100).required(), description: joi.string().allow(null, '').required(), - tags: joi.array().allow(null, ''), - projectId: joi.number().integer().required() + name: joi.string().min(3).max(100).required(), + projectId: joi.number().integer().required(), + tags: joi.array().allow(null, '') }); export const createLogValidation = joi.object({ diff --git a/Utils/cache.js b/Utils/cache.js index b4371a6..f2a9899 100644 --- a/Utils/cache.js +++ b/Utils/cache.js @@ -1,20 +1,12 @@ import NodeCache from 'node-cache'; const cache = new NodeCache({ checkperiod: 120 }); -const get = (key) => { - return cache.get(key); -}; +const get = (key) => cache.get(key); -const set = (key, data, ttl) => { - return cache.set(key, data, ttl); -}; +const set = (key, data, ttl) => cache.set(key, data, ttl); -const del = (key) => { - return cache.del(key); -}; +const del = (key) => cache.del(key); -const keys = () => { - return cache.keys(); -}; +const keys = () => cache.keys(); -export default { get, set, del, keys }; +export default { del, get, keys, set }; diff --git a/Utils/dataBaseConnection.js b/Utils/dataBaseConnection.js index 9509d28..d949b05 100644 --- a/Utils/dataBaseConnection.js +++ b/Utils/dataBaseConnection.js @@ -1,69 +1,106 @@ -import { Sequelize, DataTypes } from 'sequelize'; -import paginate from '#utils/pagination.js'; import mysql from 'mysql'; -// Main -import Customer from '#user/Models/Customer.js'; -import Unverified from '#user/Models/Unverified.js'; +import { DataTypes, Sequelize } from 'sequelize'; -// Tenant -import Role from '#user/Models/RolePermission/Role.js'; -import Permission from '#user/Models/RolePermission/Permission.js'; -import User from '#user/Models/User.js'; -import UserRole from '#user/Models/RolePermission/UserRole.js'; import Project from '#project/Models/Project.js'; import UserProject from '#project/Models/UserProject.js'; +import Job from '#scheduler/Models/job.js'; +import JobManager from '#scheduler/Models/JobManager.js'; +import Column from '#testcase/Models/Environment/Column.js'; +import Environment from '#testcase/Models/Environment/Environment.js'; +import ExecutionHistory from '#testcase/Models/ExecutionHistory/ExecutionHistory.js'; +import ProcessHistory from '#testcase/Models/ExecutionHistory/ProcessHistory.js'; +import TestStepHistory from '#testcase/Models/ExecutionHistory/TestStepHistory.js'; import Machine from '#testcase/Models/Machine.js'; - -// TestCase -import TestCase from '#testcase/Models/TestCase.js'; -import TestParameter from '#testcase/Models/TestParameter.js'; -import TestStep from '#testcase/Models/TestStep.js'; +import Object from '#testcase/Models/Object/Object.js'; +import ObjectLocator from '#testcase/Models/Object/ObjectLocator.js'; +import ObjectLog from '#testcase/Models/Object/ObjectLog.js'; import Process from '#testcase/Models/Process.js'; import ReusableProcess from '#testcase/Models/ReusableProcess.js'; import ReusableProcessLog from '#testcase/Models/ReusableProcessLog.js'; +import TestCase from '#testcase/Models/TestCase.js'; import TestCaseLog from '#testcase/Models/TestCaseLog.js'; - -// Object -import Object from '#testcase/Models/Object/Object.js'; -import ObjectLocator from '#testcase/Models/Object/ObjectLocator.js'; -import ObjectLog from '#testcase/Models/Object/ObjectLog.js'; - -// Execution History -import ExecutionHistory from '#testcase/Models/ExecutionHistory/ExecutionHistory.js'; -import ProcessHistory from '#testcase/Models/ExecutionHistory/ProcessHistory.js'; -import TestStepHistory from '#testcase/Models/ExecutionHistory/TestStepHistory.js'; - -// Environment -import Environment from '#testcase/Models/Environment/Environment.js'; -import Column from '#testcase/Models/Environment/Column.js'; - -// Execution Suite import ExecutionSuite from '#testcase/Models/TestExecution/ExecutionSuite.js'; import TestCaseExecutionMapping from '#testcase/Models/TestExecution/TestCaseExecutionMapping.js'; +import TestParameter from '#testcase/Models/TestParameter.js'; +import TestStep from '#testcase/Models/TestStep.js'; +import Customer from '#user/Models/Customer.js'; +import Permission from '#user/Models/RolePermission/Permission.js'; +import Role from '#user/Models/RolePermission/Role.js'; +import UserRole from '#user/Models/RolePermission/UserRole.js'; +import Unverified from '#user/Models/Unverified.js'; +import User from '#user/Models/User.js'; +import overrideConsole from '#utils/Logger/console.js'; +import paginate from '#utils/pagination.js'; -// Scheduler -import Job from '#scheduler/Models/job.js'; -import JobManager from '#scheduler/Models/JobManager.js'; +overrideConsole(); + +const createDBConnection = async (data) => { + try { + /* + * Console.log("Connection Details: ") + * console.log(connectionData) + */ + const { host, port, dialect, user, password, db: database } = data; + + if ((!host || !port || !dialect || user, !password || !database)) throw new Error('Insuffiecient Connection Details'); + const sequelizenew = new Sequelize(database, user, password, { + dialect, + dialectOptions: { + ssl: { + rejectUnauthorized: false, + require: true + } + }, + host, + logging: false, + pool: { + acquire: 60000, + evict: 10000, + idle: 10000, + max: 50, + min: 1 + }, + port + }); -import { overrideConsole } from '#utils/logger.js'; + await sequelizenew + .authenticate() + .then(() => console.success(`Database Connected: ${dialect} => ${host}:${port}`)) + .catch((err) => { + console.error('Sequalize Error'); + console.log(data); + console.error(err); + }); -overrideConsole(); + return sequelizenew; + } catch (err) { + console.error(err); + } +}; +const customModelMethods = (models) => { + for (const modelName in models) { + if (Object.prototype.hasOwnProperty.call(models, modelName)) { + const model = models[modelName]; + paginate(model); + } + } +}; const connection = mysql.createConnection({ host: process.env.DATABASE_HOST, + password: process.env.DATABASE_PASS, port: process.env.DATABASE_PORT, - user: process.env.DATABASE_USER, - password: process.env.DATABASE_PASS + user: process.env.DATABASE_USER }); connection.query(`CREATE DATABASE IF NOT EXISTS \`${process.env.DATABASE_PREFIX + process.env.DATABASE_NAME}\`;`); const sequelize = await createDBConnection({ db: process.env.DATABASE_PREFIX + process.env.DATABASE_NAME, - user: process.env.DATABASE_USER, - password: process.env.DATABASE_PASS, + dialect: 'mysql', host: process.env.DATABASE_HOST, + password: process.env.DATABASE_PASS, port: process.env.DATABASE_PORT, - dialect: 'mysql' + user: process.env.DATABASE_USER }); const db = {}; @@ -111,69 +148,22 @@ db.testCaseExecutionMappings = TestCaseExecutionMapping(sequelize, DataTypes); db.jobs = Job(sequelize, DataTypes); db.jobManagers = JobManager(sequelize, DataTypes); -db.machines = Machine(sequelize, DataTypes); // all associations - -db.customers.schema(process.env.DATABASE_PREFIX + process.env.DATABASE_NAME).sync({ force: false, alter: true }); -db.unverifieds.schema(process.env.DATABASE_PREFIX + process.env.DATABASE_NAME).sync({ force: false, alter: true }); -// console.log("Updaing Schema") -// db.jobs -// .schema("automation_master") -// .sync({ force: true, alter: true }) -// db.jobManagers -// .schema("automation_master") -// .sync({ force: true, alter: true }) - -// await db.scheduler.schema("automation_").sync({ alter: true, }); +// All associations +db.machines = Machine(sequelize, DataTypes); + +db.customers.schema(process.env.DATABASE_PREFIX + process.env.DATABASE_NAME).sync({ alter: true, force: false }); +db.unverifieds.schema(process.env.DATABASE_PREFIX + process.env.DATABASE_NAME).sync({ alter: true, force: false }); +/* + * Console.log("Updaing Schema") + * db.jobs + * .schema("automation_master") + * .sync({ force: true, alter: true }) + * db.jobManagers + * .schema("automation_master") + * .sync({ force: true, alter: true }) + */ + +// Await db.scheduler.schema("automation_").sync({ alter: true, }); customModelMethods(db.sequelize.models); export default db; - -async function createDBConnection (data) { - try { - // console.log("Connection Details: ") - // console.log(connectionData) - const { host, port, dialect, user, password, db } = data; - - if ((!host || !port || !dialect || user, !password || !db)) throw new Error('Insuffiecient Connection Details'); - const sequelize = new Sequelize(db, user, password, { - host, - dialect, - port, - logging: false, - dialectOptions: { - ssl: { - require: true, // This will help you. But you will see nwe error - rejectUnauthorized: false // This line will fix new error - } - }, - pool: { - max: 50, - min: 1, - acquire: 60000, - idle: 10000, - evict: 10000 - } - }); - - await sequelize - .authenticate() - .then(() => { - return console.success(`Database Connected: ${dialect} => ${host}:${port}`); - }) - .catch((err) => { - console.error('Sequalize Error'); - console.log(data); - console.error(err); - }); - - return sequelize; - } catch (err) { - console.error(err); - } -} -function customModelMethods (models) { - for (const modelName in models) { - const model = models[modelName]; - paginate(model); - } -} diff --git a/Utils/error.js b/Utils/error.js index ea184d9..f0a3c20 100644 --- a/Utils/error.js +++ b/Utils/error.js @@ -30,10 +30,10 @@ const getError = (e, res, tokenType) => { message = `Invalid ${error.path} is not a valid Integer`; break; case 'min': - message = `${error.path} must be >= ` + error.validatorArgs[0]; + message = `${error.path} must be >= ${error.validatorArgs[0]}`; break; case 'max': - message = `${error.path} must be <= ` + error.validatorArgs[0]; + message = `${error.path} must be <= ${error.validatorArgs[0]}`; break; default: message = 'Something Went Wrong'; @@ -71,9 +71,8 @@ const getError = (e, res, tokenType) => { message = e.message; } return res.status(code).json({ error: message }); - } else { - return res.status(500).json(e); } + return res.status(500).json(e); }; export default getError; diff --git a/Utils/jwt.js b/Utils/jwt.js index 561cf1b..690c177 100644 --- a/Utils/jwt.js +++ b/Utils/jwt.js @@ -6,7 +6,6 @@ const createToken = (data, secret, expiration) => { try { const options = {}; if (expiration) options.expiresIn = expiration; - console.log('saransh', secret); return sign(data, secret, options); } catch (err) { console.error('Error in Signing Token'); @@ -22,16 +21,18 @@ const getTokenError = (e, type) => { return `Invalid ${type} Found`; } }; -const extractToken = (req) => { - return req.headers.authorization || ''; - // if (req.headers.authorization && req.headers.authorization.split(" ")[0] === "Bearer") { - // return req.headers.authorization.split(" ")[1]; - // } else return null; -}; +const extractToken = (req) => + req.headers.authorization || '' + /* + * If (req.headers.authorization && req.headers.authorization.split(" ")[0] === "Bearer") { + * return req.headers.authorization.split(" ")[1]; + * } else return null; + */ +; const decryptJwt = (jwt) => { if (!jwt || typeof jwt !== 'string') return {}; return verify(jwt, process.env.JWT_ACCESS_SECRET); }; -export { createToken, getTokenError, extractToken, decryptJwt }; +export { createToken, decryptJwt, extractToken, getTokenError }; diff --git a/Utils/logger.js b/Utils/logger.js deleted file mode 100644 index ba7e331..0000000 --- a/Utils/logger.js +++ /dev/null @@ -1,114 +0,0 @@ -import chalk from 'chalk'; -import morganBody from 'morgan-body'; - -const overrideInfo = () => { - if (process.env.PRINT_CONSOLE_INFO === 'false') { - return (console.log = function () {}); - } - - const log = console.log; - console.log = function (...e) { - try { - throw new Error(); - } catch (error) { - const fileName = getFileNameFromError(error); - log.apply(console, ['\n', '[' + new Date().toLocaleString() + ']', chalk.blue('INFO:'), fileName, ...e]); - } - }; -}; - -const overrideWarn = () => { - if (process.env.PRINT_CONSOLE_WARN === 'false') { - return (console.warn = function () {}); - } - const log = console.warn; - try { - throw new Error(); - } catch (error) { - console.warn = function (...e) { - const fileName = getFileNameFromError(error); - log.apply(console, ['\n', '[' + new Date().toLocaleString() + ']', chalk.yellow('WARN:'), fileName, ...e]); - }; - } -}; - -const overrideError = () => { - if (process.env.PRINT_CONSOLE_ERROR === 'false') { - return (console.error = function () {}); - } - const log = console.error; - console.error = function (...e) { - try { - throw new Error(); - } catch (error) { - const fileName = getFileNameFromError(error); - log.apply(console, ['\n', '[' + new Date().toLocaleString() + ']', chalk.red('ERROR:'), fileName, ...e]); - } - }; -}; - -const overrideDebug = () => { - if (process.env.PRINT_CONSOLE_DEBUG === 'false') { - return (console.debug = function () {}); - } - - const log = console.debug; - console.debug = function (...e) { - try { - throw new Error(); - } catch (error) { - const fileName = getFileNameFromError(error); - log.apply(console, ['\n', '[' + new Date().toLocaleString() + ']', chalk.magenta('DEBUG:'), fileName, ...e]); - } - }; -}; - -const overrideSuccess = () => { - if (process.env.PRINT_CONSOLE_SUCCESS === 'false') { - return (console.success = function () {}); - } - - const log = console.info; - - console.success = function (...e) { - try { - throw new Error(); - } catch (error) { - const fileName = getFileNameFromError(error); - log.apply(console, ['\n', '[' + new Date().toLocaleString() + ']', chalk.green('SUCCESS:'), fileName, ...e]); - } - }; -}; - -const morgalApiLogger = (app) => { - if (process.env.PRINT_API_REQ_RES === 'false') return console.log('API logger is turned OFF'); - console.log('API logger is turned ON'); - morganBody(app, { - prettify: false, - includeNewLine: true, - timezone: 'Asia/Kolkata', - logReqHeaderList: ['x-project-id'], - skip: (req) => { - return req.url.includes('management') || req.url.includes('favicon') || req.method === 'OPTIONS'; - } - }); -}; - -const overrideConsole = () => { - overrideInfo(); - overrideWarn(); - overrideError(); - overrideSuccess(); - overrideDebug(); -}; - -const setupLogger = (app) => { - morgalApiLogger(app); - overrideConsole(); -}; -export default setupLogger; -export { morgalApiLogger, overrideConsole }; - -const getFileNameFromError = (error) => { - return '[' + error.stack.split('\n')[2].split('/').at(-1).replace(/\)/, '') + ']'; -}; diff --git a/Utils/pagination.js b/Utils/pagination.js index 73cab0e..6bec33a 100644 --- a/Utils/pagination.js +++ b/Utils/pagination.js @@ -1,20 +1,22 @@ import { Op } from 'sequelize'; -const paginate = function (model) { - model.paginate = async function (args) { +const paginate = (model) => { + model.paginate = async (args) => { const where = args.where || {}; - const page = args.page; - const size = args.size; + const { page } = args; + const { size } = args; const sort = args.sort || ''; const searchable = args.searchable || []; const database = args.database || process.env.DATABASE_PREFIX + process.env.DATABASE_NAME; const data = { where }; const query = { page: page - 1, size, sort }; - // const newPage = parseInt(query.page) - 1; - // const size = parseInt(query.size); - // const sort = query.sort; + /* + * Const newPage = parseInt(query.page) - 1; + * const size = parseInt(query.size); + * const sort = query.sort; + */ - const search = query.search; + const { search } = query; if (!(isNaN(page) || isNaN(size) || page <= 0 || size < 1)) { data.offset = parseInt(query.page * size); data.limit = parseInt(size); @@ -28,9 +30,7 @@ const paginate = function (model) { } if (searchable.length && search) { data.where = { - [Op.or]: searchable.map((el) => { - return { [el]: { [Op.like]: `%${search}%` } }; - }) + [Op.or]: searchable.map((el) => ({ [el]: { [Op.like]: `%${search}%` } })) }; } const temp = await model.schema(database).findAndCountAll({ ...data }); @@ -42,19 +42,19 @@ export const pageInfo = (info, query = {}, searchable = []) => { const currentPage = parseInt(query.page + 1); const size = parseInt(query.size); const totalElements = parseInt(info.count); - const sort = query.sort; - const search = query.search; + const { sort } = query; + const { search } = query; const pageDetails = { data, page: { - pagination: false, - totalElements, currentPage: 1, + pagination: false, size: totalElements, + totalElements, totalPages: 1 }, - sort: { sorted: false, sortBy: null, sortedBy: null }, - search: { searched: false, searchedBy: null, searchedIn: null } + search: { searched: false, searchedBy: null, searchedIn: null }, + sort: { sortBy: null, sorted: false, sortedBy: null } }; if (typeof currentPage === 'number' && currentPage > 0 && size > 0) { diff --git a/Utils/string.js b/Utils/string.js index d4e97fb..3247efd 100644 --- a/Utils/string.js +++ b/Utils/string.js @@ -1,14 +1,14 @@ -function singularize (word) { +const singularize = (word) => { const endings = { - ves: 'fe', - ies: 'y', + es: 'e', i: 'us', - zes: 'ze', + ies: 'y', + s: '', ses: 's', - es: 'e', - s: '' + ves: 'fe', + zes: 'ze' }; return word.replace(new RegExp(`(${Object.keys(endings).join('|')})$`), (r) => endings[r]); -} +}; export { singularize }; diff --git a/index.js b/index.js index 76315b7..a1d3517 100644 --- a/index.js +++ b/index.js @@ -1,14 +1,15 @@ +import parser from 'body-parser'; import express from 'express'; -import helmet from 'helmet'; import fileupload from 'express-fileupload'; -import parser from 'body-parser'; -import { defaultMiddleware } from '#middlewares/default.js'; -import { registerRoutes } from '#routes/index.js'; +import helmet from 'helmet'; + import errorContstants from '#constants/error.js'; -import { morgalApiLogger } from '#utils/logger.js'; -import { setupTimeout, setupRateLimiter, setupCors, setupResponseInterceptor, setupErrorInterceptor, setupValidationErrorInterceptor } from '#middlewares/server.js'; +import defaultMiddleware from '#middlewares/default.js'; +import { setupCors, setupErrorInterceptor, setupRateLimiter, setupResponseInterceptor, setupTimeout, setupValidationErrorInterceptor } from '#middlewares/server.js'; +import registerRoutes from '#routes/index.js'; import { syncDatabase } from '#user/Service/database.js'; -// import { scheduleInit } from "#scheduler/Service/schedulerService.js"; +import morgalApiLogger from '#utils/Logger/api.js'; +// Import { scheduleInit } from "#scheduler/Service/schedulerService.js"; const app = express(); if (process.env.PRINT_ENV === 'true') { @@ -17,6 +18,13 @@ if (process.env.PRINT_ENV === 'true') { console.debug('======================ENV======================'); } +/* + * Console.log(a); + * console.log('safa '); + * console; + * function process () { } + */ + app.use(parser.json()); app.use(parser.urlencoded({ extended: false })); app.use(helmet()); @@ -40,10 +48,8 @@ if (process.env.NODE_ENV === 'production') { syncDatabase(process.env.DATABASE_PREFIX + process.env.DATABASE_NAME); } -app.use((req, res) => { - return res.status(404).json({ error: errorContstants.ENDPOINT_NOT_FOUND }); -}); +app.use((req, res) => res.status(404).json({ error: errorContstants.ENDPOINT_NOT_FOUND })); app.listen(process.env.PORT, () => { console.success(`Server started on PORT ${process.env.PORT} PROCESS_ID ${process.pid}`); - // scheduleInit(); + // ScheduleInit(); }); diff --git a/package-lock.json b/package-lock.json index 1dbd1c1..30b1ea9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -47,6 +47,10 @@ "eslint-plugin-promise": "^6.1.1", "eslint-plugin-react": "^7.34.1", "eslint-plugin-react-hooks": "^4.6.0", + "eslint-plugin-simple-import-sort": "^12.1.0", + "eslint-plugin-sort-imports-es6-autofix": "^0.6.0", + "eslint-plugin-sort-keys-fix": "^1.1.2", + "eslint-plugin-unused-imports": "^3.1.0", "prettier": "^3.1.0" } }, @@ -3217,6 +3221,104 @@ "semver": "bin/semver.js" } }, + "node_modules/eslint-plugin-simple-import-sort": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-simple-import-sort/-/eslint-plugin-simple-import-sort-12.1.0.tgz", + "integrity": "sha512-Y2fqAfC11TcG/WP3TrI1Gi3p3nc8XJyEOJYHyEPEGI/UAgNx6akxxlX74p7SbAQdLcgASKhj8M0GKvH3vq/+ig==", + "dev": true, + "peerDependencies": { + "eslint": ">=5.0.0" + } + }, + "node_modules/eslint-plugin-sort-imports-es6-autofix": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-sort-imports-es6-autofix/-/eslint-plugin-sort-imports-es6-autofix-0.6.0.tgz", + "integrity": "sha512-2NVaBGF9NN+727Fyq+jJYihdIeegjXeUUrZED9Q8FVB8MsV3YQEyXG96GVnXqWt0pmn7xfCZOZf3uKnIhBrfeQ==", + "dev": true, + "peerDependencies": { + "eslint": ">=7.7.0" + } + }, + "node_modules/eslint-plugin-sort-keys-fix": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/eslint-plugin-sort-keys-fix/-/eslint-plugin-sort-keys-fix-1.1.2.tgz", + "integrity": "sha512-DNPHFGCA0/hZIsfODbeLZqaGY/+q3vgtshF85r+YWDNCQ2apd9PNs/zL6ttKm0nD1IFwvxyg3YOTI7FHl4unrw==", + "dev": true, + "dependencies": { + "espree": "^6.1.2", + "esutils": "^2.0.2", + "natural-compare": "^1.4.0", + "requireindex": "~1.2.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eslint-plugin-sort-keys-fix/node_modules/acorn": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", + "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/eslint-plugin-sort-keys-fix/node_modules/eslint-visitor-keys": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", + "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/eslint-plugin-sort-keys-fix/node_modules/espree": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-6.2.1.tgz", + "integrity": "sha512-ysCxRQY3WaXJz9tdbWOwuWr5Y/XrPTGX9Kiz3yoUXwW0VZ4w30HTkQLaGx/+ttFjF8i+ACbArnB4ce68a9m5hw==", + "dev": true, + "dependencies": { + "acorn": "^7.1.1", + "acorn-jsx": "^5.2.0", + "eslint-visitor-keys": "^1.1.0" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/eslint-plugin-unused-imports": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-unused-imports/-/eslint-plugin-unused-imports-3.1.0.tgz", + "integrity": "sha512-9l1YFCzXKkw1qtAru1RWUtG2EVDZY0a0eChKXcL+EZ5jitG7qxdctu4RnvhOJHv4xfmUf7h+JJPINlVpGhZMrw==", + "dev": true, + "dependencies": { + "eslint-rule-composer": "^0.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "peerDependencies": { + "@typescript-eslint/eslint-plugin": "6 - 7", + "eslint": "8" + }, + "peerDependenciesMeta": { + "@typescript-eslint/eslint-plugin": { + "optional": true + } + } + }, + "node_modules/eslint-rule-composer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/eslint-rule-composer/-/eslint-rule-composer-0.3.0.tgz", + "integrity": "sha512-bt+Sh8CtDmn2OajxvNO+BX7Wn4CIWMpTRm3MaiKPCQcnnlm0CS2mhui6QaoeQugs+3Kj2ESKEEGJUdVafwhiCg==", + "dev": true, + "engines": { + "node": ">=4.0.0" + } + }, "node_modules/eslint-scope": { "version": "7.2.2", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", @@ -5462,6 +5564,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/requireindex": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/requireindex/-/requireindex-1.2.0.tgz", + "integrity": "sha512-L9jEkOi3ASd9PYit2cwRfyppc9NoABujTP8/5gFcbERmo5jUoAKovIC3fsF17pkTnGsrByysqX+Kxd2OTNI1ww==", + "dev": true, + "engines": { + "node": ">=0.10.5" + } + }, "node_modules/resolve": { "version": "1.22.8", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", diff --git a/package.json b/package.json index 09f3004..ab5241e 100644 --- a/package.json +++ b/package.json @@ -54,6 +54,10 @@ "eslint-plugin-promise": "^6.1.1", "eslint-plugin-react": "^7.34.1", "eslint-plugin-react-hooks": "^4.6.0", + "eslint-plugin-simple-import-sort": "^12.1.0", + "eslint-plugin-sort-imports-es6-autofix": "^0.6.0", + "eslint-plugin-sort-keys-fix": "^1.1.2", + "eslint-plugin-unused-imports": "^3.1.0", "prettier": "^3.1.0" }, "imports": { diff --git a/swagger.js b/swagger.js index 2e2b5e1..98161ce 100644 --- a/swagger.js +++ b/swagger.js @@ -30,22 +30,22 @@ const endpointsFiles = [ ]; const doc = { + basePath: '/', + consumes: ['application/json'], + host: 'localhost:3001', info: { - version: '1.0.0', + description: 'Automateum', title: 'Automation Api Structure', - description: 'Automateum' + version: '1.0.0' }, - host: 'localhost:3001', - basePath: '/', - schemes: ['http', 'https'], - consumes: ['application/json'], produces: ['application/json'], + schemes: ['http', 'https'], securityDefinitions: { apiKeyAuth: { - type: 'apiKey', + description: 'Enter your Bearer Token', in: 'header', name: 'Authorization', - description: 'Enter your Bearer Token' + type: 'apiKey' } } };