Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Adding linter for consistent code style #20

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions backend/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
module.exports = {
env: {
browser: true,
commonjs: true,
es2021: true,
},
extends: 'google',
overrides: [
{
env: {
node: true,
},
files: [
'.eslintrc.{js,cjs}',
],
parserOptions: {
sourceType: 'script',
},
},
],
parserOptions: {
ecmaVersion: 'latest',
},
rules: {
'require-jsdoc': 0,
},
};
214 changes: 110 additions & 104 deletions backend/controllers/VendorController.js
Original file line number Diff line number Diff line change
@@ -1,142 +1,148 @@
const express = require('express');
const db = require('../database');

var { hash, genSalt } = require('bcryptjs');
const {hash, genSalt} = require('bcryptjs');
const bcrypt = require('bcryptjs');

const getVendor = async (req, res, next) => {
try {
const data = await db.oneOrNone('SELECT * FROM Vendors WHERE email = $1', [req.body.email]);
if (data) {
res.locals.data = data;
next();
} else {
res.status(401).json({ message: "Email does not exist." });
}
} catch (err) {
console.error(err);
res.status(500).json({ error: "Internal Server Error" });
try {
const data = await db.oneOrNone(
'SELECT * FROM Vendors WHERE email = $1',
[req.body.email],
);

if (data) {
res.locals.data = data;
next();
} else {
res.status(401).json({message: 'Email does not exist.'});
}
} catch (err) {
console.error(err);
res.status(500).json({error: 'Internal Server Error'});
}
};

// Middleware to authenticate the vendor
const authenticateVendor = async (req, res, next) => {
try {
const vendor = res.locals.data;
const match = await bcrypt.compare(req.body.password, vendor.password);
if (match) {
// If the password matches, store a success message and relevant vendor data
res.locals.data = {
status: 'success',
message: 'Successful login.',
vendorDetails: {
id: vendor.id,
email: vendor.email,
// TODO: Include any other vendor details we need
}
};
next();
} else {
res.status(401).json({ message: "Incorrect email or password." });
}
} catch (err) {
console.error(err);
res.status(500).json({ error: "Internal Server Error" });
try {
const vendor = res.locals.data;
const match = await bcrypt.compare(req.body.password, vendor.password);
if (match) {
// If the password matches, store a success message and relevant vendor data
res.locals.data = {
status: 'success',
message: 'Successful login.',
vendorDetails: {
id: vendor.id,
email: vendor.email,
// TODO: Include any other vendor details we need
},
};
next();
} else {
res.status(401).json({message: 'Incorrect email or password.'});
}
} catch (err) {
console.error(err);
res.status(500).json({error: 'Internal Server Error'});
}
};

const getVendors = async (req, res, next) => {
try {
// Retrieve all vendors from the database
const vendors = await db.manyOrNone('SELECT * FROM Vendors');
try {
// Retrieve all vendors from the database
const vendors = await db.manyOrNone('SELECT * FROM Vendors');

// If vendors are found, add them to res.locals.data
if (vendors.length) {
res.locals.data = vendors;
next(); // Proceed to the next middleware or route handler
} else {
// If no vendors are found, send a message indicating this
res.status(404).json({ message: "No vendors found" });
}
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal Server Error" });
// If vendors are found, add them to res.locals.data
if (vendors.length) {
res.locals.data = vendors;
next(); // Proceed to the next middleware or route handler
} else {
// If no vendors are found, send a message indicating this
res.status(404).json({message: 'No vendors found'});
}
} catch (error) {
console.error(error);
res.status(500).json({error: 'Internal Server Error'});
}
};

const getVendorById = async (req, res, next) => {
const { vendor_id } = req.params;
const {vendorId} = req.params;

try {
const vendor = await db.oneOrNone('SELECT * FROM Vendors WHERE vendor_id = $1', [vendor_id]);
if (vendor) {
// Store the vendor data in res.locals.data for the middleware
res.locals.data = vendor;
next(); // Pass control to the next middleware
} else {
res.status(404).json({ message: "Vendor not found" });
}
} catch (err) {
console.error(err);
res.status(500).json({ error: "Internal Server Error" });
try {
const vendor = await db.oneOrNone(
'SELECT * FROM Vendors WHERE vendor_id = $1',
[vendorId],
);
if (vendor) {
// Store the vendor data in res.locals.data for the middleware
res.locals.data = vendor;
next(); // Pass control to the next middleware
} else {
res.status(404).json({message: 'Vendor not found'});
}
} catch (err) {
console.error(err);
res.status(500).json({error: 'Internal Server Error'});
}
};

//Registers the vendor in the database
// Registers the vendor in the database
const createVendor = async (req, res, next) => {
//Get the values from the request body
const {
name,
email,
phone_number,
password,
website
} = req.body;
// Get the values from the request body
const {
name,
email,
phone_number,
password,
website,
} = req.body;

//Checks if the required fields are present
if (!password || !email || !name) {
console.log(req.body);
return res.status(400).json({ error: 'Missing required fields' });
}
// Checks if the required fields are present
if (!password || !email || !name) {
console.log(req.body);
return res.status(400).json({error: 'Missing required fields'});
}

//Hashes the password using bcrypt
let password_hash = undefined;
try {
const salt = await genSalt(10);
password_hash = await hash(password, salt);
} catch (err) {
console.log(err);
res.status(500).json({ error: err });
return;
}
// Hashes the password using bcrypt
let passwordHash;
try {
const salt = await genSalt(10);
passwordHash = await hash(password, salt);
} catch (err) {
console.log(err);
res.status(500).json({error: err});
return;
}

//Inserts the vendor into the database
try {
await db.none(
'INSERT INTO Vendors (\
// Inserts the vendor into the database
try {
await db.none(
'INSERT INTO Vendors (\
name, \
email, \
phone_number, \
password, \
website\
) VALUES ($1, $2, $3, $4, $5)',
[name, email, phone_number, password_hash, website]
);
} catch (err) {
//Duplicate emails are not allowed
if (err.code === '23505') {
res.status(400).json({ error: 'A vendor with that email already exists' });
return;
}

//Other internal error
console.log(err);
res.status(500).json({ error: err });
return;
[name, email, phone_number, passwordHash, website],
);
} catch (err) {
// Duplicate emails are not allowed
if (err.code === '23505') {
res.status(400).json({error: 'A vendor with that email already exists'});
return;
}

next();
};
// Other internal error
console.log(err);
res.status(500).json({error: err});
return;
}

next();
};

module.exports = { getVendor, getVendors, createVendor, getVendorById, authenticateVendor }
module.exports = {getVendor, getVendors, createVendor, getVendorById, authenticateVendor};
15 changes: 9 additions & 6 deletions backend/database.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
//Import the pg-promise library and initialize it
// Import the pg-promise library and initialize it
const pgp = require('pg-promise')();

//Connect to the database using the environment variable DATABASE_URL
if(process.env.DATABASE_URL === undefined) throw new Error("DATABASE_URL environment variable not set");
// Connect to the database using the environment variable DATABASE_URL
if (process.env.DATABASE_URL === undefined) {
throw new Error('DATABASE_URL environment variable not set');
}

const db = pgp(process.env.DATABASE_URL);

/*
The database object above represents a connection to our database. However,
The database object above represents a connection to our database. However,
it isn't actually connected yet. The object is an abstraction of the connection.
When you run a query against db, it will automatically connect to the database
and release it when its finished.

This database object should be the only one in the application. We import
the file where we need to make queries.
the file where we need to make queries.
*/

module.exports = db;
module.exports = db;
36 changes: 20 additions & 16 deletions backend/index.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,37 @@
// Load the environment variables from the .env file in the backend root folder
if(require('dotenv').config().parsed === undefined)
throw new Error("Could not load environment variables");

// Load the environment variables from the .env file in the backend root folder
if (require('dotenv').config().parsed === undefined) {
throw new Error('Could not load environment variables');
}

// Import the database object from the database.js file
const db = require('./database');

//Import Express and initialize our app
const express = require('express')
// Import Express and initialize our app
const express = require('express');
const app = express();

const errorHandler = require('errorhandler')
const errorHandler = require('errorhandler');
app.use(errorHandler({dumbExceptions: true, showStack: true}));


//Parse Json requests
// Parse Json requests
app.use(express.json());

//Import router objects and direct the app to use them
// Import router objects and direct the app to use them
const VendorRouter = require('./routes/VendorRouter');

app.use('/vendors', VendorRouter);

app.get('/', (req, res) => {
res.status(202).send('Hello World!')
})
res.status(202).send('Hello World!');
});

/*
The backend should be listening on port 3000 within its container,
but the container's port 3000 is mapped externally to 3001.

TL;DR the backend is running on port 3001 on the host machine.
*/

//The backend should be listening on port 3000 within its container, but the container's port 3000 is mapped externally to 3001.
// TL;DR the backend is running on port 3001 on the host machine.
app.listen(process.env.BACKEND_PORT, () => {
console.log(`PIM backend app listening on port ${process.env.BACKEND_PORT}`)
})
console.log(`PIM backend app listening on port ${process.env.BACKEND_PORT}`);
});
19 changes: 12 additions & 7 deletions backend/middleware/successResponse.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
// successResponse.js
function sendSuccessResponse(req, res) {
if (res.locals.data) {
res.status(200).json(res.locals.data);
} else {
// Fallback if no data is set in res.locals, but middleware is called
res.status(200).json({ status: 'success', message: 'Operation completed successfully.' });
}
if (res.locals.data) {
res.status(200).json(res.locals.data);
} else {
// Fallback if no data is set in res.locals, but middleware is called
res.status(200).json(
{
status: 'success',
message: 'Operation completed successfully.',
},
);
}
}

module.exports = sendSuccessResponse;
module.exports = sendSuccessResponse;
Loading
Loading