diff --git a/js/photoloader.js b/js/photoloader.js index 5340ce57..da75bcd7 100644 --- a/js/photoloader.js +++ b/js/photoloader.js @@ -1,8 +1,6 @@ // Динамічне визначення базового URL для запитів const baseUrl = window.location.origin; - - // Запит на отримання фотографій fetch(`${baseUrl}/photos`) .then(response => { diff --git a/js/server.js b/js/server.js index a4fd0a78..5b0a6a67 100644 --- a/js/server.js +++ b/js/server.js @@ -2,107 +2,32 @@ const express = require('express'); const multer = require('multer'); const path = require('path'); const cors = require('cors'); -const fs = require('fs'); -const db = require('./firebase'); - -const bodyParser = require('body-parser'); -const upload = multer({ dest: 'uploads/' }); - +const { v4: uuidv4 } = require('uuid'); const { Storage } = require('@google-cloud/storage'); +const db = require('./firebase'); // Підключення до Firestore + const storage = new Storage(); const bucket = storage.bucket('west-decor.appspot.com'); // замініть на ваш bucket -const { v4: uuidv4 } = require('uuid'); - const app = express(); -// const PORT = process.env.PORT || 3000; - -// Налаштування CORS app.use(cors()); app.use(express.json()); -app.use(express.urlencoded({ extended: true })); // Додаємо для обробки form-data +app.use(express.urlencoded({ extended: true })); + +// Налаштування для зберігання в пам'яті +const upload = multer({ storage: multer.memoryStorage() }); // Налаштування статичних файлів -// app.use('/uploads', express.static(path.join(__dirname, 'uploads'))); app.use('/css', express.static(path.join(__dirname, '../css'))); app.use('/img', express.static(path.join(__dirname, '../img'))); app.use('/js', express.static(path.join(__dirname, '../js'))); -// Перевірка та створення директорії uploads -// const uploadDir = path.join(__dirname, 'uploads'); -// if (!fs.existsSync(uploadDir)) { -// fs.mkdirSync(uploadDir, { recursive: true }); -// } - -// Налаштування для зберігання файлів -// const storage = multer.diskStorage({ -// destination: (req, file, cb) => { -// cb(null, uploadDir); -// }, -// filename: (req, file, cb) => { -// cb(null, Date.now() + path.extname(file.originalname)); -// }, -// }); - -// const upload = multer({ storage: storage }); - -// Функція для читання photos.json -// const readPhotosJson = () => { -// const filePath = path.join(__dirname, 'photos.json'); -// if (!fs.existsSync(filePath)) { -// fs.writeFileSync(filePath, JSON.stringify([])); // Створити файл, якщо його немає -// } -// const data = fs.readFileSync(filePath); -// return JSON.parse(data); -// }; - -// Функція для запису у photos.json -// const writePhotosJson = (photos) => { -// const filePath = path.join(__dirname, 'photos.json'); -// fs.writeFileSync(filePath, JSON.stringify(photos, null, 2)); -// }; - -// Маршрути для відображення HTML-сторінок -app.get('/', (req, res) => { - res.sendFile(path.join(__dirname, '../index.html')); -}); - -app.get('/about', (req, res) => { - res.sendFile(path.join(__dirname, '../about.html')); -}); - -app.get('/admin', (req, res) => { - res.sendFile(path.join(__dirname, '../admin.html')); -}); - -// Обробка запиту на завантаження фото -// app.post('/upload', upload.single('photo'), (req, res) => { -// console.log("Запит на завантаження фото отримано"); // Лог для підтвердження запиту -// console.log("Дані форми:", req.body); -// console.log("Файл:", req.file); - -// const { description, decorName, price } = req.body; -// if (req.file) { -// const photos = readPhotosJson(); -// const newPhoto = { -// name: req.file.filename, -// url: `${req.protocol}://${req.get('host')}/uploads/${req.file.filename}`, -// description: description || 'Опис відсутній', -// decorName: decorName || 'Назва декору відсутня', -// price: price ? parseFloat(price) : 0 -// }; -// photos.push(newPhoto); -// writePhotosJson(photos); - -// console.log("Фото успішно збережено:", newPhoto); // Лог для підтвердження збереження -// res.status(200).json({ message: 'Фото успішно завантажено!', file: newPhoto }); -// } else { -// console.log("Фото не завантажено"); // Лог для випадку, коли файл не завантажено -// res.status(400).json({ message: 'Не вдалося завантажити фото.' }); -// } -// }); +// Маршрути для HTML-сторінок +app.get('/', (req, res) => res.sendFile(path.join(__dirname, '../index.html'))); +app.get('/about', (req, res) => res.sendFile(path.join(__dirname, '../about.html'))); +app.get('/admin', (req, res) => res.sendFile(path.join(__dirname, '../admin.html'))); -// Отримання списку фото +// Отримання списку фото з Firestore app.get('/photos', async (req, res) => { try { const photosSnapshot = await db.collection('photos').get(); @@ -114,17 +39,12 @@ app.get('/photos', async (req, res) => { } }); - -// Додавання нового фото - - - - +// Завантаження нового фото app.post('/upload', upload.single('photo'), (req, res) => { const { description, decorName, price } = req.body; if (req.file) { const uniqueToken = uuidv4(); - const blob = bucket.file(`uploads/${req.file.filename}`); + const blob = bucket.file(`uploads/${req.file.originalname}`); const blobStream = blob.createWriteStream({ metadata: { contentType: req.file.mimetype, @@ -143,7 +63,7 @@ app.post('/upload', upload.single('photo'), (req, res) => { const publicUrl = `https://firebasestorage.googleapis.com/v0/b/${bucket.name}/o/${encodeURIComponent(blob.name)}?alt=media&token=${uniqueToken}`; const newPhoto = { - name: req.file.filename, + name: req.file.originalname, url: publicUrl, description: description || 'Опис відсутній', decorName: decorName || 'Назва декору відсутня', @@ -166,32 +86,28 @@ app.post('/upload', upload.single('photo'), (req, res) => { } }); - - -// Видалення фото +// Видалення фото з Firestore app.delete('/photos/:name', async (req, res) => { - const photoName = req.params.name; - - try { - const photoSnapshot = await db.collection('photos').where('name', '==', photoName).get(); - - if (photoSnapshot.empty) { - return res.status(404).json({ message: 'Фото не знайдено.' }); - } + const photoName = req.params.name; + try { + const photoSnapshot = await db.collection('photos').where('name', '==', photoName).get(); + if (photoSnapshot.empty) { + return res.status(404).json({ message: 'Фото не знайдено.' }); + } - photoSnapshot.forEach(async doc => { - await doc.ref.delete(); - }); - - res.status(200).json({ message: 'Фото успішно видалено.' }); - } catch (error) { - console.error('Помилка видалення фото з Firestore:', error); - res.status(500).json({ message: 'Не вдалося видалити фото.' }); - } + photoSnapshot.forEach(async doc => { + await doc.ref.delete(); + }); + + res.status(200).json({ message: 'Фото успішно видалено.' }); + } catch (error) { + console.error('Помилка видалення фото з Firestore:', error); + res.status(500).json({ message: 'Не вдалося видалити фото.' }); + } }); - +// Запуск сервера const PORT = process.env.PORT || 3000; app.listen(PORT, () => { - console.log(`Server is running on port ${PORT}`); -}); \ No newline at end of file + console.log(`Server is running on port ${PORT}`); +});