favorites.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const express = require('express');
  2. const { sequelize } = require('../models');
  3. const { QueryTypes } = require('sequelize');
  4. const jwt = require('jsonwebtoken');
  5. const JWT_SECRET = process.env.JWT_SECRET;
  6. const router = express.Router();
  7. const authenticateJWT = (req, res, next) => {
  8. const authHeader = req.headers.authorization
  9. if (authHeader) {
  10. const token = authHeader.split(' ')
  11. if (token[0].toLowerCase() != 'bearer')
  12. return res.status(400).send('не поддерживаемый тип авторизации')
  13. jwt.verify(token[1], JWT_SECRET, (err, data) => {
  14. if (err) return res.status(403).send(err)
  15. req.user = data
  16. next()
  17. })
  18. } else {
  19. res.status(401).send('нет заголовка авторизации')
  20. }
  21. }
  22. router.get('/', [authenticateJWT], async (req, res) => {
  23. try {
  24. const favorites = await sequelize.query(`
  25. SELECT f.favorite_id, h.hall_name, p.full_name as photographer_name
  26. FROM favorites f
  27. LEFT JOIN halls h ON f.hall_id = h.hall_id
  28. LEFT JOIN photographers p ON f.photographer_id = p.photographer_id
  29. WHERE f.client_id = :clientId
  30. `, {
  31. replacements: { clientId: req.user.id },
  32. type: QueryTypes.SELECT
  33. });
  34. res.json(favorites);
  35. } catch (error) {
  36. res.status(500).send(error.message);
  37. }
  38. });
  39. router.post('/', [authenticateJWT], async (req, res) => {
  40. const { hall_id, photographer_id } = req.body;
  41. try {
  42. await sequelize.query(`
  43. INSERT INTO favorites (client_id, hall_id, photographer_id)
  44. VALUES (:clientId, :hallId, :photographerId)
  45. `, {
  46. replacements: {
  47. clientId: req.user.id,
  48. hallId: hall_id || null,
  49. photographerId: photographer_id || null
  50. },
  51. type: QueryTypes.INSERT
  52. });
  53. res.status(201).send('Добавлено в избранное');
  54. } catch (error) {
  55. res.status(500).send(error.message);
  56. }
  57. });
  58. module.exports = router;