-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget-access-token.ts
More file actions
97 lines (87 loc) · 2.01 KB
/
get-access-token.ts
File metadata and controls
97 lines (87 loc) · 2.01 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
91
92
93
94
95
96
97
// https://www.rfc-editor.org/rfc/rfc6749#section-5
/**
* OAuth credentials from
* https://github.com/organizations/<org>/settings/apps/<app>
*/
export interface ClientCredentials {
id: string;
secret: string;
}
export interface AccessTokenRequest {
client: ClientCredentials;
code: string;
userAgent?: string;
}
export function accessTokenRequest(x: AccessTokenRequest): Request {
const headers = new Headers();
headers.set("Accept", "application/json");
headers.set("Content-Type", "application/json");
if (x.userAgent !== undefined) headers.set("User-Agent", x.userAgent);
return new Request("https://github.com/login/oauth/access_token", {
method: "POST",
body: JSON.stringify({
client_id: x.client.id,
client_secret: x.client.secret,
code: x.code,
}),
headers,
});
}
export type AccessTokenResponse =
| ({ success: true } & AccessTokenSuccess)
| ({ success: false } & AccessTokenFailure);
export interface AccessTokenSuccess {
accessToken: string;
object: object;
status: number;
}
export interface AccessTokenFailure {
fetchError?: unknown;
jsonError?: unknown;
status?: number;
object?: object;
}
export async function getAccessToken(
x: AccessTokenRequest,
): Promise<AccessTokenResponse> {
const request = accessTokenRequest(x);
let response: Response | undefined;
let fetchError: unknown;
try {
response = await fetch(request);
} catch (e) {
fetchError = e;
}
let object: object | undefined;
let jsonError: unknown;
try {
const value = await response?.json();
if (typeof value === 'object' && value !== null) {
object = value
} else {
jsonError = 'JSON response body is not an object'
}
} catch (e) {
jsonError = e;
}
if (
response?.ok &&
object !== undefined &&
"access_token" in object &&
typeof object.access_token === "string"
)
return {
success: true,
accessToken: object.access_token,
status: response.status,
object,
};
else
return {
success: false,
status: response?.status,
object,
fetchError,
jsonError,
};
}