DGCServerVerifier/src/Services/SettingsDownloader/RuleDownloader.ts

43 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-09-24 15:21:24 +02:00
import fs from 'fs/promises';
import axios, { AxiosResponse } from 'axios';
2021-09-23 15:38:13 +02:00
export class RuleDownloader {
static instance: RuleDownloader;
private readonly baseUrl = 'https://get.dgc.gov.it';
private readonly timeSpan = 86400000;
2021-09-24 15:21:24 +02:00
private readonly keyStorage = 'rules.json'
public rules:unknown[] = []
2021-09-23 15:38:13 +02:00
2021-09-24 15:21:24 +02:00
public async getRules(): Promise<unknown[]> {
let data = '{}';
try {
const file = await fs.open(this.keyStorage,'r');
2021-09-25 12:06:54 +02:00
data = (await file.readFile()).toString('utf-8') || '{}';
2021-09-24 15:21:24 +02:00
await file.close();
const savedData = JSON.parse(data);
if(savedData.lastupdateDate == null || Date.now() - savedData?.lastupdateDate > this.timeSpan){
await this.getSettings();
} else {
this.rules = savedData.rules;
}
return this.rules;
} catch (error) {
2021-09-26 15:42:30 +02:00
if(error.message == 'ENOENT: no such file or directory, open \'rules.json\''){
await fs.writeFile(this.keyStorage,'{}');
return this.getRules();
2021-09-24 15:21:24 +02:00
}
2021-09-23 15:38:13 +02:00
}
}
2021-09-24 15:21:24 +02:00
private async getSettings(): Promise<unknown[]>{
const response:AxiosResponse<unknown[]> = await axios.get(`${this.baseUrl}/v1/dgc/settings`);
const jsonData = response.data;
2021-09-23 15:38:13 +02:00
// this.rules = Rule.fromJSON(jsonData,{valueSets, validationClock:new Date().toISOString(),})
this.rules = jsonData;
2021-09-24 15:21:24 +02:00
// localStorage.setItem(this.keyStorage, JSON.stringify({rules:this.rules,lastupdateDate:Date.now()}));
const file = await fs.open(this.keyStorage,'w');
2021-09-26 15:42:30 +02:00
await file.writeFile(JSON.stringify({rules:this.rules,lastupdateDate:Date.now()}));
2021-09-24 15:21:24 +02:00
await file.close();
2021-09-23 15:38:13 +02:00
return jsonData;
}
}