Request wine front & backend talk nicer togheter.

- requestWineController validates wine object and returns helpfull
 error repsonse if anything is missing.
 - requestWine uses new endpoint and calls api from within itself.
 - Linting.
This commit is contained in:
2021-02-19 00:26:21 +01:00
parent a37c08880c
commit 83d9b30048
3 changed files with 169 additions and 116 deletions

View File

@@ -1,24 +1,20 @@
const path = require("path");
const RequestedWine = require(path.join(
__dirname, "/schemas/RequestedWine"
));
const Wine = require(path.join(
__dirname, "/schemas/Wine"
));
const RequestedWine = require(path.join(__dirname, "/schemas/RequestedWine"));
const Wine = require(path.join(__dirname, "/schemas/Wine"));
class RequestedWineNotFound extends Error {
constructor(message="Wine with this id was not found.") {
constructor(message = "Wine with this id was not found.") {
super(message);
this.name = "RequestedWineNotFound";
this.statusCode = 404;
}
}
const addNew = async (wine) => {
let thisWineIsLOKO = await Wine.findOne({id: wine.id})
const addNew = async wine => {
let foundWine = await Wine.findOne({ id: wine.id });
if(thisWineIsLOKO == undefined){
thisWineIsLOKO = new Wine({
if (foundWine == undefined) {
foundWine = new Wine({
name: wine.name,
vivinoLink: wine.vivinoLink,
rating: null,
@@ -26,44 +22,44 @@ const addNew = async (wine) => {
image: wine.image,
id: wine.id
});
await thisWineIsLOKO.save()
await foundWine.save();
}
let requestedWine = await RequestedWine.findOne({ "wineId": wine.id})
let requestedWine = await RequestedWine.findOne({ wineId: wine.id });
if(requestedWine == undefined){
if (requestedWine == undefined) {
requestedWine = new RequestedWine({
count: 1,
wineId: wine.id,
wine: thisWineIsLOKO
})
wine: foundWine
});
} else {
requestedWine.count += 1;
}
await requestedWine.save()
await requestedWine.save();
return requestedWine;
}
};
const getById = (id) => {
return RequestedWine.findOne({ wineId: id }).populate("wine")
const getById = id => {
return RequestedWine.findOne({ wineId: id })
.populate("wine")
.then(wine => {
if (wine == null) {
throw new RequestedWineNotFound();
}
return wine;
})
}
});
};
const deleteById = (id) => {
return getById(id)
.then(wine => RequestedWine.deleteOne({ wineId: wine.id }))
}
const deleteById = id => {
return getById(id).then(requestedWine => RequestedWine.deleteOne({ _id: requestedWine._id }));
};
const getAll = () => {
return RequestedWine.find({}).populate("wine");
}
};
module.exports = {
addNew,