Ajout de données météo
This commit is contained in:
58
tools/lib/weather/providers/index.js
Normal file
58
tools/lib/weather/providers/index.js
Normal file
@@ -0,0 +1,58 @@
|
||||
const { WEATHER_FIELDS, hasValue } = require("../constants");
|
||||
const { createInfluxProvider } = require("./influxdb");
|
||||
const { createOpenMeteoProvider } = require("./open-meteo");
|
||||
|
||||
function mergeWeather(target, addition, providerName) {
|
||||
let added = false;
|
||||
|
||||
for (const field of WEATHER_FIELDS) {
|
||||
if (!hasValue(addition[field])) continue;
|
||||
if (hasValue(target[field])) continue;
|
||||
|
||||
target[field] = addition[field];
|
||||
added = true;
|
||||
}
|
||||
|
||||
if (added) {
|
||||
const existing = target.source || [];
|
||||
const nextSources = Array.from(new Set([...existing, ...(addition.source || [providerName])].filter(Boolean)));
|
||||
target.source = nextSources;
|
||||
}
|
||||
|
||||
return added;
|
||||
}
|
||||
|
||||
function buildProviders(config) {
|
||||
const providers = [];
|
||||
const influx = createInfluxProvider(config.providers?.influxdb, config);
|
||||
const openMeteo = createOpenMeteoProvider(config.providers?.openMeteo, config);
|
||||
|
||||
if (influx) providers.push(influx);
|
||||
if (openMeteo) providers.push(openMeteo);
|
||||
|
||||
return providers;
|
||||
}
|
||||
|
||||
async function fetchWeather(targetDateTime, config) {
|
||||
const providers = buildProviders(config);
|
||||
const weather = {};
|
||||
|
||||
for (const provider of providers) {
|
||||
const result = await provider.fetch({ target: targetDateTime });
|
||||
|
||||
if (!result) continue;
|
||||
|
||||
mergeWeather(weather, result, provider.name);
|
||||
|
||||
const complete = WEATHER_FIELDS.every((field) => hasValue(weather[field]));
|
||||
if (complete) break;
|
||||
}
|
||||
|
||||
return Object.keys(weather).length > 0 ? weather : null;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
fetchWeather,
|
||||
hasConfiguredProvider: (config) => buildProviders(config).length > 0,
|
||||
mergeWeather,
|
||||
};
|
||||
Reference in New Issue
Block a user