Refactoring day2 (error handling)

This commit is contained in:
2020-08-22 19:24:33 +02:00
parent b907489a75
commit bf2a9cbf1e
5 changed files with 110 additions and 116 deletions

View File

@@ -8,6 +8,7 @@ import routeRestaurant from "../routes/routeRestaurant.js";
import routeUser from "../routes/routeUser.js";
import routeSearch from "../routes/routeSearch.js";
import routeImg from "../routes/routeImg.js";
import routeTest from "../routes/routeTest.js";
export default ({ app, secret }) => {
const limiter = rateLimiter({
@@ -29,6 +30,7 @@ export default ({ app, secret }) => {
app.use("/img", routeImg);
app.use("/user", routeUser);
app.use("/search", routeSearch);
app.use("/test", routeTest);
return app;
};

View File

@@ -1,7 +1,6 @@
import express from "express";
import * as services from "../services/services.js";
import Restaurant from "../models/restaurant.js";
import Dish from "../models/dish.js";
import sanitizer from "string-sanitizer";
import mongoose from "mongoose";
@@ -65,25 +64,8 @@ router.get("/dishes", async (req, res) => {
const query = services.decodeAndSanitize(req.query.restaurantId);
await services.validateRestaurant(query);
let restaurant = await services.fetchRestaurant(query);
let dishesCount = restaurant.dishes.length;
let dishes = [];
let dishes2 = await services.fetchAllDishesForRestaurant(restaurant);
console.log(dishes2);
restaurant.dishes.forEach((element) => {
Dish.findById(element._id, (err, result) => {
if (err) {
res.sendStatus(500);
} else {
if (result === null) {
dishesCount--;
if (dishes.length == dishesCount) res.send(dishes);
} else {
dishes.push(result);
if (dishes.length == dishesCount) res.send(dishes);
}
}
});
});
let dishes = await services.fetchAllDishesForRestaurant(restaurant);
res.send(dishes);
} catch (error) {
console.log(error);
res.sendStatus(400);

17
routes/routeTest.js Normal file
View File

@@ -0,0 +1,17 @@
import express from "express";
import * as services from "../services/services.js";
var router = express.Router();
router.post("/", async (req, res) => {
await services
.fetchUser()
.then((response) => {
res.send(response);
})
.catch((e) => {
services.handleError(e, res);
});
});
export default router;

View File

@@ -16,66 +16,47 @@ var error = function (err) {
console.log("Task failed successfully");
};
router.post("/login", (req, res) => {
if (req.body.password && req.body.email) {
services.fetchUser(req.body.email, (result) => {
if (!result) {
res.sendStatus(404);
} else {
var user = result;
bcrypt.compare(req.body.password, user.password, function (
err,
result
) {
if (err) {
res.sendStatus(500);
} else {
if (result) {
const userNoPass = {
firstname: user.firstname,
lastname: user.lastname,
email: user.email,
id: user._id,
};
var token = services.generateAuthToken(userNoPass);
res.header("x-auth-token", token).status(202).send(userNoPass);
} else {
res.sendStatus(401);
}
}
});
}
});
} else {
res.sendStatus(404);
// LOGIN
router.post("/login", async (req, res) => {
try {
if (!req.body.password || !req.body.email) {
throw services.newError("No input data", 204);
}
const user = await services.fetchUser(req.body.email);
/* await services.checkPassword(req.body.password, user.password);
const userNoPass = {
firstname: user.firstname,
lastname: user.lastname,
email: user.email,
id: user._id,
};
var token = services.generateAuthToken(userNoPass);
res.header("x-auth-token", token).status(202).send(userNoPass); */
res.send(user);
} catch (error) {
services.handleError(error, res);
}
});
router.post("/register", (req, res) => {
services.checkEmailTaken(req.body.email, (result) => {
if (result) {
res.sendStatus(409);
} else {
services.hashPass(req.body.password, (hashedPass) => {
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
password: hashedPass,
firstname: req.body.firstname,
lastname: req.body.lastname,
});
user.save((err) => {
if (err) {
res.sendStatus(500);
} else {
const contact = services.composeNewContact(user);
agileAPI.contactAPI.add(contact, success, error);
res.sendStatus(201);
}
});
});
}
});
// REGISTER
router.post("/register", async (req, res) => {
try {
await services.checkEmailTaken(req.body.email);
const password = await services.hashPass(req.body.password);
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
password: password,
firstname: req.body.firstname,
lastname: req.body.lastname,
});
await user.save();
const contact = services.composeNewContact(user);
agileAPI.contactAPI.add(contact, success, error);
res.sendStatus(201);
} catch (e) {
services.handleError(e, res);
}
});
export default router;

View File

@@ -9,8 +9,24 @@ import bcrypt from "bcrypt";
import * as config from "../config/index.js";
const { jwtSecret } = config;
export function newError(message, status) {
const error = {
message: message,
status: status,
};
return error;
}
export function handleError(error, responseObject) {
if (!error.message) {
responseObject.sendStatus(500);
} else {
responseObject.status(error.status).send(error.message);
}
}
export async function validateRestaurant(id) {
if (!mongoose.Types.ObjectId.isValid(id)) throw "Invalid ID";
if (!mongoose.Types.ObjectId.isValid(id)) throw newError("Invalid ID", 204);
let valid = await Restaurant.exists({ _id: id });
if (valid !== true) throw "Restaurant doesn't exist";
return true;
@@ -28,31 +44,23 @@ export async function fetchRestaurant(id) {
export async function fetchAllDishesForRestaurant(restaurant) {
let dishes = [];
await restaurant.dishes.forEach((element) => {
Dish.findById(element._id, (err, result) => {
if (err) {
console.log(err);
} else {
dishes.push(result);
console.log(result);
}
});
});
for (const dish of restaurant.dishes) {
let res = await fetchDish(dish._id);
if (res !== null) dishes.push(res);
}
return dishes;
}
export async function fetchDish(id) {
foo;
let data = await Dish.findById(id).catch((e) => {
throw `Couldn't fetch ${id}`;
});
return data;
}
export function fetchUser(email, callback) {
User.findOne({ email: email }, (err, res) => {
if (err || res === null) {
callback(false);
} else {
callback(res);
}
});
export async function fetchUser(email) {
if (!email) throw newError("No input", 404);
User.findOne({ email: email });
}
export function decodeAndSanitize(query) {
@@ -60,6 +68,10 @@ export function decodeAndSanitize(query) {
return sanitizer.sanitize.keepUnicode(decodeURI(query));
}
export async function checkPassword(password, hash) {
bcrypt.compare(password, hash);
}
export function generateAuthToken(user) {
const token = jwt.sign(
{
@@ -75,14 +87,17 @@ export function generateAuthToken(user) {
return token;
}
export function checkEmailTaken(email, callback) {
User.exists({ email: email }, (err, res) => {
if (err) {
callback(false);
} else {
callback(res);
}
});
export async function checkEmailTaken(email) {
if (!email) throw newError("No input email", 204);
await User.exists({ email: email })
.then((res) => {
if (res) {
throw newError("Email is taken", 409);
}
})
.catch((e) => {
throw e;
});
}
export function validateUserToken(token) {
@@ -179,17 +194,14 @@ export function halfYearFromNowDate() {
return toShortDate(resultDate);
}
export function hashPass(pass, callback) {
bcrypt.genSalt(10, (err, salt) => {
if (err) callback(false);
bcrypt.hash(pass, salt, function (err, hash) {
if (err) {
callback(false);
} else {
callback(hash);
}
});
});
export async function hashPass(pass) {
try {
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(pass, salt);
return hash;
} catch (error) {
throw newError("Internal error", 500);
}
}
export function dueDateBasedOnSubscription(subscriptionActive) {