feat: Оптимизация маршрутов для получения данных из S3 с использованием вспомогательных функций getS3JsonWithHeaders и getS3TextWithHeaders для улучшения читаемости и обработки ошибок. Упрощение кода и улучшение обработки конфигураций серверов и фильтров.
Publish Fast Tabler Docker image / build-and-push-fast (push) Successful in 1m34s

This commit is contained in:
2025-10-03 02:08:23 +07:00
parent b80bd402a2
commit a4bd1ab1d4
10 changed files with 922 additions and 190 deletions
+17 -65
View File
@@ -3,10 +3,11 @@
*/
const { s3, BUCKET_NAME, writeS3TextObject, deleteS3Object, headMeta } = require('../services/s3Service');
const { sendError, sendOk, checkIfNoneMatch } = require('../middleware/errorHandler');
const { GetObjectCommand, HeadObjectCommand, DeleteObjectCommand } = require('@aws-sdk/client-s3');
const { sendError, sendOk } = require('../middleware/errorHandler');
const { GetObjectCommand, DeleteObjectCommand } = require('@aws-sdk/client-s3');
const { streamToString } = require('../services/s3Service');
const { createJsonDataRoutes } = require('./jsonDataRoutes');
const { getS3TextWithHeaders, getS3JsonWithHeaders } = require('../utils/s3Helpers');
// GET /api/server-configs (список серверов)
const serverConfigsListRoutes = createJsonDataRoutes('server-configs.json', (server, i) => {
@@ -19,33 +20,15 @@ const serverConfigsListRoutes = createJsonDataRoutes('server-configs.json', (ser
// GET /api/server-configs/:serverId (конкретная конфигурация)
async function getServerConfig(req, res) {
const { serverId } = req.params;
try {
const head = await s3.send(new HeadObjectCommand({
Bucket: BUCKET_NAME,
Key: `filter-manager/config-${serverId}.txt`
})).catch(() => null);
const etag = head?.ETag || null;
if (etag) res.set('ETag', String(etag));
if (head?.LastModified) res.set('Last-Modified', new Date(head.LastModified).toUTCString());
if (typeof head?.ContentLength === 'number') res.set('Content-Length-Source', String(head.ContentLength));
if (checkIfNoneMatch(req, res, etag)) return;
const data = await s3.send(new GetObjectCommand({
Bucket: BUCKET_NAME,
Key: `filter-manager/config-${serverId}.txt`
}));
const config = await streamToString(data.Body);
res.json({ config });
} catch (error) {
if (error.code === 'NoSuchKey' || error?.$metadata?.httpStatusCode === 404) {
res.json({ config: '// Конфигурация не найдена' });
} else {
console.error(error);
return sendError(res, 500, 'Error reading server config from S3', 'E_S3');
await getS3TextWithHeaders(
`filter-manager/config-${serverId}.txt`,
req,
res,
{
transform: (text) => ({ config: text }),
defaultValue: '// Конфигурация не найдена'
}
}
);
}
// POST /api/server-configs/:serverId (сохранить конфигурацию)
@@ -100,43 +83,12 @@ async function deleteServerComplete(req, res) {
// GET /api/server-filters/:serverId
async function getServerFilters(req, res) {
const { serverId } = req.params;
try {
const head = await s3.send(new HeadObjectCommand({
Bucket: BUCKET_NAME,
Key: `filter-manager/server-filters-${serverId}.json`
})).catch(() => null);
const etag = head?.ETag || null;
if (etag) res.set('ETag', String(etag));
if (head?.LastModified) res.set('Last-Modified', new Date(head.LastModified).toUTCString());
if (typeof head?.ContentLength === 'number') res.set('Content-Length-Source', String(head.ContentLength));
if (checkIfNoneMatch(req, res, etag)) return;
const data = await s3.send(new GetObjectCommand({
Bucket: BUCKET_NAME,
Key: `filter-manager/server-filters-${serverId}.json`
}));
const fileContent = await streamToString(data.Body);
let filters = [];
try {
filters = JSON.parse(fileContent);
if (!Array.isArray(filters)) filters = [];
} catch (parseError) {
console.error('Error parsing server filters:', parseError);
filters = [];
}
res.json(filters);
} catch (error) {
if (error.code === 'NoSuchKey') {
res.json([]);
} else {
console.error(error);
return sendError(res, 500, 'Error reading server filters from S3', 'E_S3');
}
}
await getS3JsonWithHeaders(
`filter-manager/server-filters-${serverId}.json`,
req,
res,
{ defaultValue: [] }
);
}
// POST /api/server-filters/:serverId