0
0
Fork 0
qnips-probeaufgabe/src/app/database-ha.service.ts

48 lines
1.4 KiB
TypeScript

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import Ajv from 'ajv';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import type { Speiseplan } from './database-ha-interface';
import { emptySpeiseplan, speiseplanSchema } from './database-ha-interface';
/** Speiseplan API endpoint */
const ENDPOINT = 'https://my.qnips.io/dbapi/ha';
@Injectable({
providedIn: 'root',
})
export class DatabaseHaService {
private validateSpeiseplan: Ajv.ValidateFunction;
constructor(private http: HttpClient) {
const ajv = new Ajv();
this.validateSpeiseplan = ajv.compile(speiseplanSchema);
}
getSpeiseplan(): Observable<Speiseplan> {
return this.http.get<Speiseplan>(ENDPOINT).pipe(
// Schema validation
map((plan) => {
if (!this.validateSpeiseplan(plan)) {
throw new Error('Speiseplan failed schema validation');
}
return plan;
}),
catchError((err) => {
console.error(err);
// TODO
// (Omitted because of the lack of surrounding application)
// This should use a better error
// reporting mechanism that is more in line
// with the surrounding application.
// TODO Localization
alert('Fehler beim laden des Speiseplans');
return of(emptySpeiseplan);
})
);
}
}