-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrequests.ts
More file actions
90 lines (77 loc) · 2.54 KB
/
requests.ts
File metadata and controls
90 lines (77 loc) · 2.54 KB
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
import type {
BannerPayload,
BannerProps,
EpicPayload,
EpicProps,
GutterPayload,
GutterProps,
HeaderPayload,
HeaderProps,
} from '../shared/types';
import type { TestTracking } from '../shared/types/abTests/shared';
export interface ModuleData<PROPS> {
name: string;
props: PROPS;
}
export interface ModuleDataResponse<PROPS> {
data?: {
module: ModuleData<PROPS>;
meta: TestTracking;
};
}
type ModuleType = 'epic' | 'liveblog-epic' | 'banner' | 'header' | 'gutter-liveblog';
const getForcedVariant = (type: ModuleType): string | null => {
if (URLSearchParams) {
const params = new URLSearchParams(window.location.search);
const value = params.get(`force-${type}`);
if (value) {
return value;
}
}
return null;
};
type Payload = EpicPayload | BannerPayload | HeaderPayload | GutterPayload;
const getModuleData = <PROPS>(
type: ModuleType,
baseUrl: string,
payload: Payload,
): Promise<ModuleDataResponse<PROPS>> => {
const forcedVariant = getForcedVariant(type);
const queryString = forcedVariant ? `?force=${forcedVariant}` : '';
const url = `${baseUrl}/${type}${queryString}`;
return fetch(url, {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
.then((response: Response) => {
if (!response.ok) {
throw Error(
response.statusText ||
`Supporter Revenue ${type} | Api call returned HTTP status ${response.status}`,
);
}
return response;
})
.then((response) => response.json());
};
export const getEpic = (
baseUrl: string,
payload: EpicPayload,
): Promise<ModuleDataResponse<EpicProps>> => getModuleData('epic', baseUrl, payload);
export const getLiveblogEpic = (
baseUrl: string,
payload: EpicPayload,
): Promise<ModuleDataResponse<EpicProps>> => getModuleData('liveblog-epic', baseUrl, payload);
export const getBanner = (
baseUrl: string,
payload: BannerPayload,
): Promise<ModuleDataResponse<BannerProps>> => getModuleData('banner', baseUrl, payload);
export const getGutterLiveblog = (
baseUrl: string,
payload: GutterPayload,
): Promise<ModuleDataResponse<GutterProps>> => getModuleData('gutter-liveblog', baseUrl, payload);
export const getHeader = (
baseUrl: string,
payload: HeaderPayload,
): Promise<ModuleDataResponse<HeaderProps>> => getModuleData('header', baseUrl, payload);