GSheetsApi / server.js
Rooni's picture
Update server.js
4c7c7b9 verified
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
app.post('/fetch-sheet', async (req, res) => {
const { key, list, page, max } = req.body;
if (!key || !list || !page || !max) {
return res.status(400).json({ error: '❌ Ошибка данных, повторите попытку.' });
}
// Экранирование значений для использования в URL
const encodedKey = encodeURIComponent(key);
const encodedList = encodeURIComponent(list);
try {
const url = `https://opensheet.elk.sh/${encodedKey}/${encodedList}`;
const response = await axios.get(url);
const data = response.data;
// Разделение данных на страницы
const startIndex = (page - 1) * max;
const endIndex = startIndex + max;
const paginatedData = data.slice(startIndex, endIndex);
res.json(paginatedData);
} catch (error) {
console.error(error);
res.status(500).json({ error: '❌ Произошла ошибка сервера при запросе данных.' });
}
});
app.post('/search', async (req, res) => {
const { key, list, search, search_key, max, page } = req.body;
if (!key || !list || !search || !search_key || !page || !max) {
return res.status(400).json({ error: '❌ Ошибка данных, повторите попытку.' });
}
const encodedKey = encodeURIComponent(key);
const encodedList = encodeURIComponent(list);
try {
const url = `https://opensheet.elk.sh/${encodedKey}/${encodedList}`;
const response = await axios.get(url);
let data = response.data;
// Фильтрация данных по строке поиска
data = data.filter(item => item[search_key] && item[search_key].toString().toLowerCase().includes(search.toLowerCase()));
// Разделение данных на страницы
const startIndex = (page - 1) * max;
const endIndex = startIndex + max;
const paginatedData = data.slice(startIndex, endIndex);
res.json(paginatedData);
} catch (error) {
console.error(error);
res.status(500).json({ error: '❌ Произошла ошибка сервера при поиске данных.' });
}
});
app.post('/random', async (req, res) => {
const { key, list, num } = req.body;
if (!key || !list || !num) {
return res.status(400).json({ error: '❌ Ошибка данных, повторите попытку.' });
}
const encodedKey = encodeURIComponent(key);
const encodedList = encodeURIComponent(list);
try {
const url = `https://opensheet.elk.sh/${encodedKey}/${encodedList}`;
const response = await axios.get(url);
let data = response.data;
// Получение случайных элементов из списка
const shuffled = data.sort(() => 0.5 - Math.random());
let selected = shuffled.slice(0, num);
res.json(selected);
} catch (error) {
console.error(error);
res.status(500).json({ error: '❌ Произошла ошибка сервера при получении случайных данных.' });
}
});
app.post('/info', async (req, res) => {
const { key, list, max } = req.body;
if (!key || !list) {
return res.status(400).json({ error: '❌ Ошибка данных, повторите попытку.' });
}
const encodedKey = encodeURIComponent(key);
const encodedList = encodeURIComponent(list);
try {
const url = `https://opensheet.elk.sh/${encodedKey}/${encodedList}`;
const response = await axios.get(url);
const data = response.data;
const maxPages = data.length;
const info = { objects: maxPages };
if (max) {
const pages = Math.ceil(maxPages / max);
info.pages = pages;
}
res.json(info);
} catch (error) {
console.error(error);
res.status(500).json({ error: '❌ Произошла ошибка сервера при получении информации.' });
}
});
const port = 7860;
app.listen(port, () => {
console.log(`API сервер запущен на порту ${port}`);
});