Skip to content

Instantly share code, notes, and snippets.

@zaheeraws
Created February 22, 2023 13:42
Show Gist options
  • Save zaheeraws/4a63bb7ff4d6f8a220173f0bcad8e056 to your computer and use it in GitHub Desktop.
Save zaheeraws/4a63bb7ff4d6f8a220173f0bcad8e056 to your computer and use it in GitHub Desktop.
import jwt from 'jsonwebtoken'
import dotenv from 'dotenv'
dotenv.config()
const varifyToken = async (req, res, next) => {
const token = req.cookies.access_token || req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ status: 401, message: "Auth token is required" });
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) return res.status(401).json({ status: 401, message: "Token is not valid" });
req.user = user;
next()
})
}
export default varifyToken;
//* Import express and initialize the routers
import express from 'express';
const router = express.Router();
//* Call the controller with the methods
import { loginUser, logoutUser, registerUser, varifyUser } from '../controllers/authController.js'
import varifyToken from '../middlewares/auth.middleware.js';
router.post('/register', registerUser);
router.post('/login', loginUser);
router.post('/varify',varifyToken, varifyUser);
router.post('/logout', logoutUser);
export default router;
import dotenv from 'dotenv'
dotenv.config()
import mysql from 'mysql';
const dbConnection = mysql.createConnection ({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password:process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
});
dbConnection.connect((error) => {
if (error) {
if (error.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Database connection was closed.');
}
if (error.code === 'ER_CON_COUNT_ERROR') {
console.error('Database has too many connections.');
}
if (error.code === 'ECONNREFUSED') {
console.error('Database connection was refused.');
}
console.log(error)
}
});
export default dbConnection;
lass ErrorHandler extends Error {
constructor(status, message) {
super();
this.status = status;
this.message = message;
}
static alreadyExists(statusCode, message) {
return new ErrorHandler(statusCode, message)
}
static unAuthorized(statusCode, message = "Unauthorized Action") {
return new ErrorHandler(statusCode, message)
}
static notFound(statusCode=404, message = "404 Not Found") {
return new ErrorHandler(statusCode, message)
}
static unCaughtError(statusCode, message) {
return new ErrorHandler(statusCode, message)
}
static serverError(statusCode=500, message = "Internal server error") {
return new ErrorHandler(statusCode, message)
}
}
export default ErrorHandler
import dbConnection from "../database/dbConnection.js";
import ErrorHandler from "../middlewares/ErrorHandler.js"
export const createPipeline = async (req, res, next) => {
const { title, status } = req.body;
const checkPipelineEsistsQuery = "SELECT * FROM pipeline WHERE title=?";
dbConnection.query(checkPipelineEsistsQuery, [title], (err, result) => {
if (err) {
return next(ErrorHandler.serverError(500, err))
}
if (result.length) {
return res.status(400).json({ status: false, message: "Pipeline already exists" })
}
const pipelineSqlQuery = "INSERT INTO pipeline(title,status) VALUES(?,?)";
try {
dbConnection.query(pipelineSqlQuery, [title, status], async (error, result) => {
if (error) {
return res.status(400).json({ status: false, message: error.sqlMessage })
}
if (result.affectedRows === 1) {
return res.status(200).json({ status: true, message: "Pipeline created successfully" })
}
})
} catch (e) {
return next(ErrorHandler.unCaughtError(400, e))
}
});
}
export const getAllPipelines = async (req, res, next) => {
try {
dbConnection.query('SELECT * from pipeline', function (error, result) {
if (error) {
return res.status(400).json({ status: false, message: error.sqlMessage })
} else {
return res.status(200).json({ status: true, result })
}
});
} catch (e) {
return next(ErrorHandler.serverError())
}
}
export const getPipelineById = async (req, res, next) => {
const { id } = req.params
if (!id || isNaN(id)) return res.status(400).json({ status: false, message: "Pipeline id is required" })
const sqlQuery = "SELECT * FROM pipeline WHERE id = ?";
try {
dbConnection.query(sqlQuery, [+id], (error, result) => {
if (error) {
return res.status(400).json({ status: false, message: error.sqlMessage })
}
if (!result.length) {
return res.status(400).json({ status: false, message: "Not found" })
}
return res.status(200).json({ status: true, result })
})
} catch (e) {
return next(ErrorHandler.serverError())
}
}
export const updatePipeline = (req, res, next) => {
const { id, title, status } = req.body;
const pipelineSqlUpdateQuery = "UPDATE pipeline SET title=?,status=? WHERE id = ?";
try {
dbConnection.query(pipelineSqlUpdateQuery, [title, status, id], async (error, result) => {
if (error) {
return res.status(400).json({ status: false, message: error.sqlMessage })
}
if (result.affectedRows === 1) {
return res.status(200).json({ status: true, message: "Pipeline updated successfully" })
}
})
} catch (e) {
return next(ErrorHandler.unCaughtError(400, e))
}
}
export const deletePipelineById = (req, res, next) => {
const { id } = req.params
if (!id || isNaN(id)) return res.status(400).json({ status: false, message: "Customer id is required" })
const sqlQuery = "DELETE FROM pipeline WHERE id = ?";
try {
dbConnection.query(sqlQuery, [+id], (error, result) => {
if (error) {
return res.status(400).json({ status: false, message: error.sqlMessage })
}
if (result.affectedRows === 1) {
return res.status(200).json({ status: true, message: "Pipeline Deleted successfully" })
} else {
return res.status(400).json({ status: false, message: "Pipeline Not found" })
}
})
} catch (e) {
return next(ErrorHandler.serverError())
}
}
//* Import the customers.routes file with all de methods
import authRoutes from './routes/auth.routes.js';
import customersRoutes from './routes/customer.routes.js';
import pipelinesRoutes from './routes/pipeline.routes.js';
import customerDataRoutes from './routes/customer-data.routes.js';
import lendersRoutes from './routes/lender.routes.js';
//* Here I defined the first endpoint
const router = (app) => {
app.use('/api/auth', authRoutes);
app.use('/api/customers', customersRoutes);
app.use('/api/pipelines', pipelinesRoutes);
app.use('/api/customer/data', customerDataRoutes);
app.use('/api/lenders', lendersRoutes);
};
export default router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment