-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathapi.service.ts
62 lines (49 loc) · 1.62 KB
/
api.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { AgendaItem, Company, Speaker, Sponsor } from '../types';
import { KeyValueStorage } from '@ionic-enterprise/secure-storage/ngx';
import { KeyService } from './key.service';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private initialized = false;
constructor(private secureStorage: KeyValueStorage, private keyService: KeyService) {
}
public async getSpeakers(): Promise<Speaker[]> {
return await this.getCached('speakers.json');
}
public async getAgenda(): Promise<AgendaItem[]> {
return await this.getCached('agenda.json');
}
public async getSponsors(): Promise<Sponsor[]> {
return await this.getCached('sponsors.json');
}
public async getCompanies(): Promise<Company[]> {
return await this.getCached('companies.json');
}
private async getCached(url: string): Promise<any> {
await this.initStorage();
// Get from Secure Storage if available
let data = await this.secureStorage.get(url);
if (!data) {
// Otherwise get from the server
data = await this.get(url);
// Store in Secure Storage
this.secureStorage.set(url, data);
}
return data;
}
private async initStorage(): Promise<void> {
if (this.initialized) {
return;
}
this.initialized = true;
const key = await this.keyService.getKey();
await this.secureStorage.create(key);
}
private async get(url: string): Promise<any> {
const response = await fetch(`${environment.baseUrl}/${url}`);
return await response.json();
}
}