-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathbootstrap-provider.ts
95 lines (79 loc) · 2.49 KB
/
bootstrap-provider.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { promises } from 'fs';
import * as fetch from 'make-fetch-happen';
import { ClientFeaturesResponse, FeatureInterface } from '../feature';
import { CustomHeaders } from '../headers';
import { buildHeaders } from '../request';
import { Segment } from '../strategy/strategy';
export interface BootstrapProvider {
readBootstrap(): Promise<ClientFeaturesResponse | undefined>;
}
export interface BootstrapOptions {
url?: string;
urlHeaders?: CustomHeaders;
filePath?: string;
data?: FeatureInterface[];
segments?: Segment[];
bootstrapProvider?: BootstrapProvider;
}
export class DefaultBootstrapProvider implements BootstrapProvider {
private url?: string;
private urlHeaders?: CustomHeaders;
private filePath?: string;
private data?: FeatureInterface[];
private segments?: Segment[];
private appName: string;
private instanceId: string;
constructor(options: BootstrapOptions, appName: string, instanceId: string) {
this.url = options.url;
this.urlHeaders = options.urlHeaders;
this.filePath = options.filePath;
this.data = options.data;
this.segments = options.segments;
this.appName = appName;
this.instanceId = instanceId;
}
private async loadFromUrl(bootstrapUrl: string): Promise<ClientFeaturesResponse | undefined> {
const response = await fetch(bootstrapUrl, {
method: 'GET',
timeout: 10_000,
headers: buildHeaders({
appName: this.appName,
instanceId: this.instanceId,
etag: undefined,
contentType: undefined,
custom: this.urlHeaders,
}),
retry: {
retries: 2,
maxTimeout: 10_000,
},
});
if (response.ok) {
return response.json();
}
return undefined;
}
private async loadFromFile(filePath: string): Promise<ClientFeaturesResponse | undefined> {
const fileContent = await promises.readFile(filePath, 'utf8');
return JSON.parse(fileContent);
}
async readBootstrap(): Promise<ClientFeaturesResponse | undefined> {
if (this.data) {
return { version: 2, segments: this.segments, features: [...this.data] };
}
if (this.url) {
return this.loadFromUrl(this.url);
}
if (this.filePath) {
return this.loadFromFile(this.filePath);
}
return undefined;
}
}
export function resolveBootstrapProvider(
options: BootstrapOptions,
appName: string,
instanceId: string,
): BootstrapProvider {
return options.bootstrapProvider || new DefaultBootstrapProvider(options, appName, instanceId);
}