-
-
Notifications
You must be signed in to change notification settings - Fork 648
/
Copy pathdim-api-helper.ts
198 lines (171 loc) · 5.12 KB
/
dim-api-helper.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import {
FatalTokenError,
getActiveToken as getBungieToken,
} from 'app/bungie-api/authenticated-fetch';
import { dedupePromise } from 'app/utils/promises';
import { HttpClientConfig } from 'bungie-api-ts/http';
const DIM_API_HOST = 'https://api.destinyitemmanager.com';
export const API_KEY = $DIM_FLAVOR !== 'dev' ? $DIM_API_KEY : localStorage.getItem('dimApiKey')!;
const localStorageKey = 'dimApiToken';
/**
* Call one of the unauthenticated DIM APIs.
*/
export async function unauthenticatedApi<T>(
config: HttpClientConfig,
noApiKey?: boolean,
): Promise<T> {
if (!noApiKey && !API_KEY) {
throw new Error('No DIM API key configured');
}
let url = `${DIM_API_HOST}${config.url}`;
if (config.params) {
// TODO: properly type HttpClientConfig
url = `${url}?${new URLSearchParams(config.params as Record<string, string>).toString()}`;
}
const headers: RequestInit['headers'] = {};
if (config.body) {
headers['Content-Type'] = 'application/json';
}
if (!noApiKey) {
headers['X-API-Key'] = API_KEY;
}
headers['X-DIM-Version'] = $DIM_VERSION;
const response = await fetch(
new Request(url, {
method: config.method,
body: config.body ? JSON.stringify(config.body) : undefined,
headers,
}),
);
if (response.status === 401) {
// Delete our token
deleteDimApiToken();
throw new FatalTokenError(`Unauthorized call to ${config.url}`);
}
if (response.ok) {
return response.json() as Promise<T>;
}
let responseData;
try {
responseData = (await response.json()) as { error: string; message: string };
} catch {}
if (responseData?.error) {
throw new Error(`${responseData.error}: ${responseData.message}`);
}
throw new Error(`Failed to call DIM API: ${response.status}`);
}
/**
* Call one of the authenticated DIM APIs.
*/
export async function authenticatedApi<T>(config: HttpClientConfig): Promise<T> {
if (!API_KEY) {
throw new Error('No DIM API key configured');
}
const token = await getAuthToken();
let url = `${DIM_API_HOST}${config.url}`;
if (config.params) {
// TODO: properly type HttpClientConfig
url = `${url}?${new URLSearchParams(config.params as Record<string, string>).toString()}`;
}
const headers: RequestInit['headers'] = {
Authorization: `Bearer ${token.accessToken}`,
'X-API-Key': API_KEY,
'X-DIM-Version': $DIM_VERSION,
};
if (config.body) {
headers['Content-Type'] = 'application/json';
}
const response = await fetch(
new Request(url, {
method: config.method,
body: config.body ? JSON.stringify(config.body) : undefined,
headers,
}),
);
if (response.status === 401) {
// Delete our token
deleteDimApiToken();
}
if (response.ok) {
return response.json() as Promise<T>;
}
let responseData;
try {
responseData = (await response.json()) as { error: string; message: string };
} catch {}
if (responseData?.error) {
throw new Error(`${responseData.error}: ${responseData.message}`);
}
throw new Error(`Failed to call DIM API: ${response.status}`);
}
export interface DimAuthToken {
/** Your DIM API access token, to be used in further requests. */
accessToken: string;
/** How many seconds from now the token will expire. */
expiresInSeconds: number;
/** A UTC epoch milliseconds timestamp representing when the token was acquired. */
inception: number;
}
/**
* Get all token information from saved storage.
*/
export function getToken(): DimAuthToken | undefined {
const tokenString = localStorage.getItem(localStorageKey);
return tokenString ? (JSON.parse(tokenString) as DimAuthToken) : undefined;
}
/**
* Save all the information about access/refresh tokens.
*/
function setToken(token: DimAuthToken) {
localStorage.setItem(localStorageKey, JSON.stringify(token));
}
export function deleteDimApiToken() {
localStorage.removeItem(localStorageKey);
}
export interface AuthTokenRequest {
/** The access token from authenticating with the Bungie.net API */
bungieAccessToken: string;
/** The user's Bungie.net membership ID */
membershipId: string;
}
const refreshToken = dedupePromise(async () => {
const bungieToken = await getBungieToken();
const authRequest: AuthTokenRequest = {
bungieAccessToken: bungieToken.accessToken.value,
membershipId: bungieToken.bungieMembershipId,
};
try {
const authToken = await unauthenticatedApi<DimAuthToken>({
url: '/auth/token',
method: 'POST',
body: authRequest,
});
authToken.inception = Date.now();
setToken(authToken);
return authToken;
} catch (e) {
if ($DIM_FLAVOR === 'dev') {
throw new FatalTokenError('DIM API Key Incorrect');
}
throw e;
}
});
async function getAuthToken(): Promise<DimAuthToken> {
const token = getToken();
if (!token || hasTokenExpired(token)) {
// Get a token!
return refreshToken();
}
return token;
}
/**
* Has the token expired, based on its 'expires' property?
*/
function hasTokenExpired(token?: DimAuthToken) {
if (!token) {
return true;
}
const expires = token.inception + token.expiresInSeconds * 1000;
const now = Date.now();
return now > expires;
}