Files
pulse-signage/src/data/api-sources.js
T
2026-07-25 02:29:19 +01:00

150 lines
4.6 KiB
JavaScript

const http = require('http');
const https = require('https');
function normalizeUpdateIntervalUnit(value) {
const unit = String(value || '').trim().toLowerCase();
return unit === 'seconds' ? 'seconds' : 'minutes';
}
async function fetchApiSourcesData(pool) {
const [apiSources] = await pool.query(
'SELECT id, name, api_url, update_interval_value, update_interval_unit, last_pulled_at, last_pull_error, last_response_status, last_response_content_type, last_response_json, created_at, modified_at, created_by, modified_by FROM api_sources ORDER BY modified_at DESC, id DESC'
);
return { apiSources: apiSources };
}
async function fetchApiSourceById(pool, id) {
const [rows] = await pool.query(
'SELECT id, name, api_url, update_interval_value, update_interval_unit, last_pulled_at, last_pull_error, last_response_status, last_response_content_type, last_response_json, created_at, modified_at, created_by, modified_by FROM api_sources WHERE id = ?',
[id]
);
return rows[0] || null;
}
async function loadUrlText(urlValue) {
if (typeof fetch === 'function') {
const response = await fetch(urlValue, {
headers: {
Accept: 'application/json, text/plain;q=0.9, */*;q=0.8',
'User-Agent': 'Pulse Signage API Reader'
}
});
return {
statusCode: response.status,
contentType: response.headers.get('content-type') || '',
bodyText: await response.text(),
ok: response.ok
};
}
return await new Promise(function (resolve, reject) {
const url = new URL(urlValue);
const transport = url.protocol === 'https:' ? https : http;
const request = transport.get(url, {
headers: {
Accept: 'application/json, text/plain;q=0.9, */*;q=0.8',
'User-Agent': 'Pulse Signage API Reader'
}
}, function (response) {
response.setEncoding('utf8');
let body = '';
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function () {
resolve({
statusCode: response.statusCode || 0,
contentType: String(response.headers['content-type'] || ''),
bodyText: body,
ok: !response.statusCode || response.statusCode < 400
});
});
response.on('error', reject);
});
request.on('error', reject);
});
}
async function fetchApiSourceResponse(apiUrl) {
const response = await loadUrlText(apiUrl);
if (!response.ok) {
throw new Error(`Unable to load API response (${response.statusCode}).`);
}
const text = String(response.bodyText || '').trim();
if (!text) {
throw new Error('API response did not return JSON.');
}
let parsed;
try {
parsed = JSON.parse(text);
} catch (_error) {
throw new Error('API response was not valid JSON.');
}
return {
responseJson: JSON.stringify(parsed, null, 2),
responseStatus: response.statusCode,
responseContentType: response.contentType
};
}
function buildApiSourcePayload(req, existingApiSource) {
const fallback = existingApiSource || {};
const name = String(req.body.name || fallback.name || '').trim();
const apiUrl = String(req.body.api_url || req.body.apiUrl || fallback.api_url || '').trim();
const updateIntervalValue = Math.max(1, Number(req.body.update_interval_value || req.body.updateIntervalValue || fallback.update_interval_value || 60));
const updateIntervalUnit = normalizeUpdateIntervalUnit(req.body.update_interval_unit || req.body.updateIntervalUnit || fallback.update_interval_unit || 'minutes');
if (!name) {
const error = new Error('API source name is required.');
error.statusCode = 400;
throw error;
}
if (!apiUrl) {
const error = new Error('API source URL is required.');
error.statusCode = 400;
throw error;
}
let parsedUrl;
try {
parsedUrl = new URL(apiUrl);
} catch (_error) {
const error = new Error('Enter a valid API URL.');
error.statusCode = 400;
throw error;
}
if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
const error = new Error('API URL must start with http or https.');
error.statusCode = 400;
throw error;
}
if (!Number.isFinite(updateIntervalValue)) {
const error = new Error('Update interval must be a number.');
error.statusCode = 400;
throw error;
}
return {
name: name,
apiUrl: parsedUrl.toString(),
updateIntervalValue: Math.floor(updateIntervalValue),
updateIntervalUnit: updateIntervalUnit
};
}
module.exports = {
fetchApiSourcesData: fetchApiSourcesData,
fetchApiSourceById: fetchApiSourceById,
fetchApiSourceResponse: fetchApiSourceResponse,
buildApiSourcePayload: buildApiSourcePayload
};