/** * Универсальные хелперы для JSON/текста из локального storage (SQLite) */ const { headMeta, readS3TextObject } = require('../services/s3Service'); const { sendError, checkIfNoneMatch } = require('../middleware/errorHandler'); /** * Универсальный GET для JSON объектов с заголовками */ async function getS3JsonWithHeaders(s3Key, req, res, options = {}) { const { transform = (data) => data, defaultValue = [] } = options; try { const head = await headMeta(s3Key); 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; let fileContent; try { const data = await readS3TextObject(s3Key); fileContent = data.body; } catch (e) { if (e?.code === 'NoSuchKey') { return res.json(transform(defaultValue)); } throw e; } let parsed; try { parsed = JSON.parse(fileContent); if (!Array.isArray(parsed) && Array.isArray(defaultValue)) { parsed = defaultValue; } } catch (parseError) { console.error(`Error parsing ${s3Key}:`, parseError); parsed = defaultValue; } const result = transform(parsed); res.json(result); } catch (error) { console.error(error); return sendError(res, 500, 'Error reading storage', 'E_STORAGE'); } } /** * Универсальный GET для текстовых объектов с заголовками */ async function getS3TextWithHeaders(s3Key, req, res, options = {}) { const { transform = (text) => ({ config: text }), defaultValue = '' } = options; try { const head = await headMeta(s3Key); 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; let text; try { const data = await readS3TextObject(s3Key); text = data.body; } catch (e) { if (e?.code === 'NoSuchKey') { return res.json(transform(defaultValue)); } throw e; } const result = transform(text); res.json(result); } catch (error) { console.error(error); return sendError(res, 500, 'Error reading storage', 'E_STORAGE'); } } module.exports = { getS3JsonWithHeaders, getS3TextWithHeaders, };