This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
FunctionProject/api/controllers/favorites.js

93 lines
2.4 KiB
JavaScript
Raw Permalink Normal View History

2020-08-03 12:04:07 +02:00
const errorHandling = require('../assets/utils/errorHandling')
const { serverError } = require('../assets/config/errors')
const Favorites = require('../models/favorites')
const Functions = require('../models/functions')
exports.getFavoriteByFunctionId = async (req, res, next) => {
2020-08-03 12:04:07 +02:00
const { functionId } = req.params
const { userId } = req
try {
const favorite = await Favorites.findOne({
where: {
userId,
functionId
}
})
if (!favorite) {
return res.status(200).json({ isFavorite: false })
}
2020-08-03 12:04:07 +02:00
return res.status(200).json({ isFavorite: true })
} catch (error) {
console.log(error)
return errorHandling(next, serverError)
}
}
exports.postFavoriteByFunctionId = async (req, res, next) => {
2020-08-03 12:04:07 +02:00
const { functionId } = req.params
const { userId } = req
try {
2020-08-03 14:14:45 +02:00
const resultFunction = await Functions.findOne({
where: { id: functionId }
})
2020-08-03 12:04:07 +02:00
if (!resultFunction) {
2020-08-03 14:14:45 +02:00
return errorHandling(next, {
message: "La fonction n'existe pas.",
statusCode: 404
})
}
2020-08-03 12:04:07 +02:00
const favorite = await Favorites.findOne({
where: {
userId,
functionId
}
})
if (!favorite) {
await Favorites.create({ userId, functionId })
return res.status(201).json({ result: 'Le favoris a bien été ajouté!' })
}
2020-08-03 14:14:45 +02:00
return errorHandling(next, {
message: 'La fonction est déjà en favoris.',
statusCode: 400
})
2020-08-03 12:04:07 +02:00
} catch (error) {
console.log(error)
return errorHandling(next, serverError)
}
}
exports.deleteFavoriteByFunctionId = async (req, res, next) => {
2020-08-03 12:04:07 +02:00
const { functionId } = req.params
const { userId } = req
try {
2020-08-03 14:14:45 +02:00
const resultFunction = await Functions.findOne({
where: { id: functionId }
})
2020-08-03 12:04:07 +02:00
if (!resultFunction) {
2020-08-03 14:14:45 +02:00
return errorHandling(next, {
message: "La fonction n'existe pas.",
statusCode: 404
})
2020-08-03 12:04:07 +02:00
}
const favorite = await Favorites.findOne({
where: {
userId,
functionId
}
})
if (!favorite) {
2020-08-03 14:14:45 +02:00
return errorHandling(next, {
message: "Le fonction n'est pas en favoris.",
statusCode: 400
})
}
2020-08-03 12:04:07 +02:00
await favorite.destroy()
2020-08-03 14:14:45 +02:00
return res
.status(200)
.json({ message: 'Le fonction a bien été supprimé des favoris.' })
2020-08-03 12:04:07 +02:00
} catch (error) {
console.log(error)
return errorHandling(next, serverError)
}
}