-
Notifications
You must be signed in to change notification settings - Fork 118
/
fetch-token.ts
50 lines (44 loc) · 1.26 KB
/
fetch-token.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
/* Copyright (c) 2017 Environmental Systems Research Institute, Inc.
* Apache-2.0 */
import {
request,
IRequestOptions,
ITokenRequestOptions
} from "@esri/arcgis-rest-request";
interface IFetchTokenRawResponse {
access_token: string;
expires_in: number;
username: string;
ssl?: boolean;
refresh_token?: string;
}
export interface IFetchTokenResponse {
token: string;
expires: Date;
username: string;
ssl: boolean;
refreshToken?: string;
}
export function fetchToken(
url: string,
requestOptions: ITokenRequestOptions
): Promise<IFetchTokenResponse> {
const options: IRequestOptions = requestOptions;
// we generate a response, so we can't return the raw response
options.rawResponse = false;
return request(url, options).then((response: IFetchTokenRawResponse) => {
const r: IFetchTokenResponse = {
token: response.access_token,
username: response.username,
expires: new Date(
// convert seconds in response to milliseconds and add the value to the current time to calculate a static expiration timestamp
Date.now() + (response.expires_in * 1000 - 1000)
),
ssl: response.ssl === true
};
if (response.refresh_token) {
r.refreshToken = response.refresh_token;
}
return r;
});
}