Refactoring day2 (error handling)
This commit is contained in:
@@ -8,6 +8,7 @@ import routeRestaurant from "../routes/routeRestaurant.js";
|
|||||||
import routeUser from "../routes/routeUser.js";
|
import routeUser from "../routes/routeUser.js";
|
||||||
import routeSearch from "../routes/routeSearch.js";
|
import routeSearch from "../routes/routeSearch.js";
|
||||||
import routeImg from "../routes/routeImg.js";
|
import routeImg from "../routes/routeImg.js";
|
||||||
|
import routeTest from "../routes/routeTest.js";
|
||||||
|
|
||||||
export default ({ app, secret }) => {
|
export default ({ app, secret }) => {
|
||||||
const limiter = rateLimiter({
|
const limiter = rateLimiter({
|
||||||
@@ -29,6 +30,7 @@ export default ({ app, secret }) => {
|
|||||||
app.use("/img", routeImg);
|
app.use("/img", routeImg);
|
||||||
app.use("/user", routeUser);
|
app.use("/user", routeUser);
|
||||||
app.use("/search", routeSearch);
|
app.use("/search", routeSearch);
|
||||||
|
app.use("/test", routeTest);
|
||||||
|
|
||||||
return app;
|
return app;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import express from "express";
|
import express from "express";
|
||||||
import * as services from "../services/services.js";
|
import * as services from "../services/services.js";
|
||||||
import Restaurant from "../models/restaurant.js";
|
import Restaurant from "../models/restaurant.js";
|
||||||
import Dish from "../models/dish.js";
|
|
||||||
import sanitizer from "string-sanitizer";
|
import sanitizer from "string-sanitizer";
|
||||||
import mongoose from "mongoose";
|
import mongoose from "mongoose";
|
||||||
|
|
||||||
@@ -65,25 +64,8 @@ router.get("/dishes", async (req, res) => {
|
|||||||
const query = services.decodeAndSanitize(req.query.restaurantId);
|
const query = services.decodeAndSanitize(req.query.restaurantId);
|
||||||
await services.validateRestaurant(query);
|
await services.validateRestaurant(query);
|
||||||
let restaurant = await services.fetchRestaurant(query);
|
let restaurant = await services.fetchRestaurant(query);
|
||||||
let dishesCount = restaurant.dishes.length;
|
let dishes = await services.fetchAllDishesForRestaurant(restaurant);
|
||||||
let dishes = [];
|
res.send(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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
res.sendStatus(400);
|
res.sendStatus(400);
|
||||||
|
|||||||
17
routes/routeTest.js
Normal file
17
routes/routeTest.js
Normal 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;
|
||||||
@@ -16,21 +16,14 @@ var error = function (err) {
|
|||||||
console.log("Task failed successfully");
|
console.log("Task failed successfully");
|
||||||
};
|
};
|
||||||
|
|
||||||
router.post("/login", (req, res) => {
|
// LOGIN
|
||||||
if (req.body.password && req.body.email) {
|
router.post("/login", async (req, res) => {
|
||||||
services.fetchUser(req.body.email, (result) => {
|
try {
|
||||||
if (!result) {
|
if (!req.body.password || !req.body.email) {
|
||||||
res.sendStatus(404);
|
throw services.newError("No input data", 204);
|
||||||
} else {
|
}
|
||||||
var user = result;
|
const user = await services.fetchUser(req.body.email);
|
||||||
bcrypt.compare(req.body.password, user.password, function (
|
/* await services.checkPassword(req.body.password, user.password);
|
||||||
err,
|
|
||||||
result
|
|
||||||
) {
|
|
||||||
if (err) {
|
|
||||||
res.sendStatus(500);
|
|
||||||
} else {
|
|
||||||
if (result) {
|
|
||||||
const userNoPass = {
|
const userNoPass = {
|
||||||
firstname: user.firstname,
|
firstname: user.firstname,
|
||||||
lastname: user.lastname,
|
lastname: user.lastname,
|
||||||
@@ -38,44 +31,32 @@ router.post("/login", (req, res) => {
|
|||||||
id: user._id,
|
id: user._id,
|
||||||
};
|
};
|
||||||
var token = services.generateAuthToken(userNoPass);
|
var token = services.generateAuthToken(userNoPass);
|
||||||
res.header("x-auth-token", token).status(202).send(userNoPass);
|
res.header("x-auth-token", token).status(202).send(userNoPass); */
|
||||||
} else {
|
res.send(user);
|
||||||
res.sendStatus(401);
|
} catch (error) {
|
||||||
}
|
services.handleError(error, res);
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
res.sendStatus(404);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post("/register", (req, res) => {
|
// REGISTER
|
||||||
services.checkEmailTaken(req.body.email, (result) => {
|
router.post("/register", async (req, res) => {
|
||||||
if (result) {
|
try {
|
||||||
res.sendStatus(409);
|
await services.checkEmailTaken(req.body.email);
|
||||||
} else {
|
const password = await services.hashPass(req.body.password);
|
||||||
services.hashPass(req.body.password, (hashedPass) => {
|
|
||||||
const user = new User({
|
const user = new User({
|
||||||
_id: new mongoose.Types.ObjectId(),
|
_id: new mongoose.Types.ObjectId(),
|
||||||
email: req.body.email,
|
email: req.body.email,
|
||||||
password: hashedPass,
|
password: password,
|
||||||
firstname: req.body.firstname,
|
firstname: req.body.firstname,
|
||||||
lastname: req.body.lastname,
|
lastname: req.body.lastname,
|
||||||
});
|
});
|
||||||
user.save((err) => {
|
await user.save();
|
||||||
if (err) {
|
|
||||||
res.sendStatus(500);
|
|
||||||
} else {
|
|
||||||
const contact = services.composeNewContact(user);
|
const contact = services.composeNewContact(user);
|
||||||
agileAPI.contactAPI.add(contact, success, error);
|
agileAPI.contactAPI.add(contact, success, error);
|
||||||
res.sendStatus(201);
|
res.sendStatus(201);
|
||||||
|
} catch (e) {
|
||||||
|
services.handleError(e, res);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
export default router;
|
export default router;
|
||||||
|
|||||||
@@ -9,8 +9,24 @@ import bcrypt from "bcrypt";
|
|||||||
import * as config from "../config/index.js";
|
import * as config from "../config/index.js";
|
||||||
const { jwtSecret } = config;
|
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) {
|
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 });
|
let valid = await Restaurant.exists({ _id: id });
|
||||||
if (valid !== true) throw "Restaurant doesn't exist";
|
if (valid !== true) throw "Restaurant doesn't exist";
|
||||||
return true;
|
return true;
|
||||||
@@ -28,31 +44,23 @@ export async function fetchRestaurant(id) {
|
|||||||
|
|
||||||
export async function fetchAllDishesForRestaurant(restaurant) {
|
export async function fetchAllDishesForRestaurant(restaurant) {
|
||||||
let dishes = [];
|
let dishes = [];
|
||||||
await restaurant.dishes.forEach((element) => {
|
for (const dish of restaurant.dishes) {
|
||||||
Dish.findById(element._id, (err, result) => {
|
let res = await fetchDish(dish._id);
|
||||||
if (err) {
|
if (res !== null) dishes.push(res);
|
||||||
console.log(err);
|
|
||||||
} else {
|
|
||||||
dishes.push(result);
|
|
||||||
console.log(result);
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
});
|
|
||||||
return dishes;
|
return dishes;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchDish(id) {
|
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) {
|
export async function fetchUser(email) {
|
||||||
User.findOne({ email: email }, (err, res) => {
|
if (!email) throw newError("No input", 404);
|
||||||
if (err || res === null) {
|
User.findOne({ email: email });
|
||||||
callback(false);
|
|
||||||
} else {
|
|
||||||
callback(res);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function decodeAndSanitize(query) {
|
export function decodeAndSanitize(query) {
|
||||||
@@ -60,6 +68,10 @@ export function decodeAndSanitize(query) {
|
|||||||
return sanitizer.sanitize.keepUnicode(decodeURI(query));
|
return sanitizer.sanitize.keepUnicode(decodeURI(query));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function checkPassword(password, hash) {
|
||||||
|
bcrypt.compare(password, hash);
|
||||||
|
}
|
||||||
|
|
||||||
export function generateAuthToken(user) {
|
export function generateAuthToken(user) {
|
||||||
const token = jwt.sign(
|
const token = jwt.sign(
|
||||||
{
|
{
|
||||||
@@ -75,13 +87,16 @@ export function generateAuthToken(user) {
|
|||||||
return token;
|
return token;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function checkEmailTaken(email, callback) {
|
export async function checkEmailTaken(email) {
|
||||||
User.exists({ email: email }, (err, res) => {
|
if (!email) throw newError("No input email", 204);
|
||||||
if (err) {
|
await User.exists({ email: email })
|
||||||
callback(false);
|
.then((res) => {
|
||||||
} else {
|
if (res) {
|
||||||
callback(res);
|
throw newError("Email is taken", 409);
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
throw e;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,17 +194,14 @@ export function halfYearFromNowDate() {
|
|||||||
return toShortDate(resultDate);
|
return toShortDate(resultDate);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function hashPass(pass, callback) {
|
export async function hashPass(pass) {
|
||||||
bcrypt.genSalt(10, (err, salt) => {
|
try {
|
||||||
if (err) callback(false);
|
const salt = await bcrypt.genSalt(10);
|
||||||
bcrypt.hash(pass, salt, function (err, hash) {
|
const hash = await bcrypt.hash(pass, salt);
|
||||||
if (err) {
|
return hash;
|
||||||
callback(false);
|
} catch (error) {
|
||||||
} else {
|
throw newError("Internal error", 500);
|
||||||
callback(hash);
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function dueDateBasedOnSubscription(subscriptionActive) {
|
export function dueDateBasedOnSubscription(subscriptionActive) {
|
||||||
|
|||||||
Reference in New Issue
Block a user