| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- const express = require('express');
- const { sequelize } = require('../models');
- const { QueryTypes } = require('sequelize');
- const jwt = require('jsonwebtoken');
- const JWT_SECRET = process.env.JWT_SECRET;
- const router = express.Router();
- const authenticateJWT = (req, res, next) => {
- const authHeader = req.headers.authorization
- if (authHeader) {
- const token = authHeader.split(' ')
- if (token[0].toLowerCase() != 'bearer')
- return res.status(400).send('не поддерживаемый тип авторизации')
- jwt.verify(token[1], JWT_SECRET, (err, data) => {
- if (err) return res.status(403).send(err)
- req.user = data
- next()
- })
- } else {
- res.status(401).send('нет заголовка авторизации')
- }
- }
- router.get('/', [authenticateJWT], async (req, res) => {
- try {
- const favorites = await sequelize.query(`
- SELECT f.favorite_id, h.hall_name, p.full_name as photographer_name
- FROM favorites f
- LEFT JOIN halls h ON f.hall_id = h.hall_id
- LEFT JOIN photographers p ON f.photographer_id = p.photographer_id
- WHERE f.client_id = :clientId
- `, {
- replacements: { clientId: req.user.id },
- type: QueryTypes.SELECT
- });
- res.json(favorites);
- } catch (error) {
- res.status(500).send(error.message);
- }
- });
- router.post('/', [authenticateJWT], async (req, res) => {
- const { hall_id, photographer_id } = req.body;
- try {
- await sequelize.query(`
- INSERT INTO favorites (client_id, hall_id, photographer_id)
- VALUES (:clientId, :hallId, :photographerId)
- `, {
- replacements: {
- clientId: req.user.id,
- hallId: hall_id || null,
- photographerId: photographer_id || null
- },
- type: QueryTypes.INSERT
- });
- res.status(201).send('Добавлено в избранное');
- } catch (error) {
- res.status(500).send(error.message);
- }
- });
- module.exports = router;
|