'use strict'; const Joi = require('joi'); const Jwt = require('@hapi/jwt'); module.exports = [ { method: 'POST', path: '/favorites/add', options: { auth: { scope : ['user', 'admin'] }, tags: ['api'], validate: { payload: Joi.object({ movieId: Joi.number().required().example(1).description('Id of the movie'), }) } }, handler: async (request, h) => { const {userService} = request.services(); const { favoriteService } = request.services(); const { movieId } = request.payload; //Search user id in the database with the email const userId = await userService.getByEmail(request.auth.credentials.email).then((user) => user.id) //If movie not exist, return error const { Movie } = request.models(); const movie = await Movie.query().findById(movieId); if(!movie) { return h.response({message: 'Movie not found'}).code(400); } //if movie already in favorite, return error const favorite = await favoriteService.getByMovieAndUser(movieId, userId); if(favorite) { return h.response({message: 'Movie already in favorite'}).code(400); } // Appelle la méthode create du favoriteService en passant les champs nécessaires return await favoriteService.create({ movie_id: movieId, user_id: userId }); } }, { method: 'GET', path: '/favorites', options: { auth: { scope : ['user', 'admin'] }, tags: ['api'] }, handler: async (request, h) => { const { Favorite } = request.models(); const { favoriteService } = request.services(); // Appelle la méthode list du favoriteService pour récupérer tous les favoris return await favoriteService.list(); } }, { method: 'DELETE', path: '/favorites/remove', options: { auth: { scope : ['user', 'admin'] }, tags: ['api'], validate: { payload: Joi.object({ movieId: Joi.number().required().example(1).description('Id of the movie'), }) } }, handler: async (request, h) => { const { userService } = request.services(); const {favoriteService} = request.services(); const {movieId} = request.payload; const userId = await userService.getByEmail(request.auth.credentials.email).then((user) => user.id) //If movie not exist, return error const { Movie } = request.models(); const movie = await Movie.query().findById(movieId); if(!movie) { return h.response({message: 'Movie not found'}).code(400); } // If the movie is not in the favorite, return an error const favorite = await favoriteService.getByMovieAndUser(movieId, userId); if(!favorite) { return h.response({message: 'Movie not in favorite'}).code(400); } // Appelle la méthode remove du favoriteService pour supprimer le favori return await favoriteService.delete({ movie_id: movieId, user_id: userId }); } } ]