82 lines
2.5 KiB
JavaScript
82 lines
2.5 KiB
JavaScript
import express from 'express';
|
|
import fetch from 'node-fetch';
|
|
import { fileURLToPath } from 'url';
|
|
import { dirname, join } from 'path';
|
|
import dotenv from 'dotenv';
|
|
|
|
// Загружаем переменные окружения
|
|
dotenv.config();
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = dirname(__filename);
|
|
|
|
const app = express();
|
|
const PORT = process.env.PORT || 3000;
|
|
|
|
// Serve static files from public directory
|
|
app.use(express.static('public'));
|
|
|
|
// API endpoint to get phone book data
|
|
async function getPhoneBookData() {
|
|
try {
|
|
const response = await fetch(process.env.API_URL, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': `Bearer ${process.env.API_TOKEN}`
|
|
},
|
|
body: JSON.stringify({
|
|
"active": true,
|
|
"fields": {
|
|
"fullname": true,
|
|
"mobile_number": true,
|
|
"fixed_number": true,
|
|
"title": true,
|
|
"department": true,
|
|
"email_string": true
|
|
},
|
|
"from": 0,
|
|
"size": parseInt(process.env.API_PAGE_SIZE) || 1000
|
|
})
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (!data.success || !data.result?.result) {
|
|
throw new Error('Неверный формат данных от API');
|
|
}
|
|
|
|
return data.result.result.map(employee => ({
|
|
name: formatFullName(employee.fullname),
|
|
phone: employee.mobile_number || employee.fixed_number || '-',
|
|
title: employee.title || '-',
|
|
department: employee.department || '-',
|
|
email: employee.email_string || '-'
|
|
}));
|
|
} catch (error) {
|
|
console.error('Ошибка при запросе к API:', error.message);
|
|
return [];
|
|
}
|
|
}
|
|
|
|
function formatFullName(fullname) {
|
|
if (!fullname) return '-';
|
|
|
|
const { lastname = '', firstname = '', middlename = '' } = fullname;
|
|
return [lastname, firstname, middlename].filter(Boolean).join(' ') || '-';
|
|
}
|
|
|
|
// API endpoint for contacts
|
|
app.get('/api/contacts', async (req, res) => {
|
|
const contacts = await getPhoneBookData();
|
|
res.json(contacts);
|
|
});
|
|
|
|
// Serve index.html for all other routes
|
|
app.get('*', (req, res) => {
|
|
res.sendFile(join(__dirname, 'public', 'index.html'));
|
|
});
|
|
|
|
app.listen(PORT, () => {
|
|
console.log(`Сервер запущен на порту ${PORT}`);
|
|
});
|