Files
readin/readdata.js
2023-10-26 16:50:13 +02:00

53 lines
1.5 KiB
JavaScript

import axios from 'axios'
import * as fs from 'fs'
import { logit, logerror} from'./logit.js'
import { DateTime } from 'luxon'
const API_URL = 'https://api.sensor.community/static/v1/data.json'; // URL to API on 'luftdaten.info'
const SAVE_NAME = './data/aktdata.json'; // filename for actual data
let LIVE = process.env.LIVE || 'true'
export let statistics = {};
export const doReadfromAPI = async () => {
logit(`LIVE = ${LIVE}`)
let start = DateTime.now()
let data = []
if (LIVE === 'true') {
logit(`Start Reading from API`)
let body
for(let count = 1; count <= 3; count++) {
try {
logit(`Try - ${count}`)
let ret = await axios(API_URL, {timeout: 10000})
if (ret.status != 200) {
continue
}
data = ret.data
saveDatatoFile(SAVE_NAME, JSON.stringify(data))
break
} catch (e) {
logerror(`doReadfromAPI ${e}`)
}
}
} else {
logit('Start using data on disk')
data = readDatafromFile(SAVE_NAME)
}
statistics.readInTime = start.diffNow('seconds').toObject().seconds * -1
statistics.entries = data.length
logit(`ReadIn-Time: ${statistics.readInTime} sec`)
return data
}
// die Daten in eimnr Datei zwischenspeichern
function saveDatatoFile(fn, data) {
fs.writeFileSync(fn, data)
}
// Daten wieder vom File lesen
function readDatafromFile(fn) {
return JSON.parse(fs.readFileSync(fn))
}