/
request.ts
101 lines (90 loc) · 2.53 KB
/
request.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
96
97
98
99
100
101
import { buildUrl } from "../../../urls";
import { RemoteServerError as _RemoteServerError } from "../../../request";
import { IDiscussionsRequestOptions } from "../types";
export class RemoteServerError extends _RemoteServerError {
error: string;
constructor(message: string, url: string, status: number, error: string) {
super(message, url, status);
this.error = error;
}
}
/**
* returns Promise that resolves token to use in Discussions API requests
*
* @export
* @param {IDiscussionsRequestOptions} options
* @return {*} {Promise<string>}
*/
export function authenticateRequest(
options: IDiscussionsRequestOptions
): Promise<string> {
const { token, authentication } = options;
let tokenPromise = () => {
return Promise.resolve(token);
};
if (authentication) {
tokenPromise = authentication.getToken.bind(
authentication,
authentication.portal
);
}
return tokenPromise();
}
/**
* parses IDiscussionsRequestOptions and makes request against Discussions API
*
* @export
* @template T
* @param {string} route
* @param {IDiscussionsRequestOptions} options
* @param {string} [token]
* @return {*} {Promise<T>}
*/
export function apiRequest<T>(
route: string,
options: IDiscussionsRequestOptions,
token?: string
): Promise<T> {
const headers = new Headers(options.headers);
headers.append("Content-Type", "application/json");
if (token) {
headers.append("Authorization", `Bearer ${token}`);
}
const opts: RequestInit = {
headers,
method: options.httpMethod || "GET",
mode: options.mode,
cache: options.cache,
credentials: options.credentials,
};
const apiBase = buildUrl({
// TODO: we _want_ to use getHubApiUrl(),
// but have to deal w/ the fact that this package overwrites IHubRequestOptions
host: options.hubApiUrl || "https://hub.arcgis.com",
path: "/api/discussions/v1",
});
if (options.data) {
if (options.httpMethod === "GET") {
const queryParams = new URLSearchParams(options.data).toString();
route += `?${queryParams}`;
} else {
opts.body = JSON.stringify(options.data);
}
}
const url = [apiBase.replace(/\/$/, ""), route.replace(/^\//, "")].join("/");
return fetch(url, opts).then((res) => {
if (res.ok) {
return res.json();
} else {
const { statusText, status } = res;
return res.json().then((err) => {
throw new RemoteServerError(
statusText,
url,
status,
JSON.stringify(err.message)
);
});
}
});
}