-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
81 lines (63 loc) · 1.84 KB
/
index.js
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
const core = require('@actions/core');
const BASE_URL = 'https://api.stainlessapi.com/api';
async function main() {
try {
const fullRepo = core.getInput('repo');
const apiKey = core.getInput('stainless-api-key');
const result = await retrieveGithubAccessToken(fullRepo, apiKey);
core.setOutput('github_access_token', result.token);
} catch (err) {
core.setFailed(`retrieve-github-access-token failed: ${err.message}`);
}
}
async function retrieveGithubAccessToken(fullRepo, apiKey) {
const [owner, repo] = fullRepo.split('/');
if (!owner || !repo) {
throw new Error(`Could not resolve owner and repo name from ${fullRepo}`);
}
if (!apiKey) {
throw new Error('Missing stainless-api-key input');
}
console.log(`Getting Github access token for`, { owner, repo });
const url = `${BASE_URL}/github-access-token`;
const res = await fetch(url, {
method: 'POST',
body: JSON.stringify({
owner,
repo,
}),
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
});
if (res.status > 299) {
throw new Error(`${url} received ${res.status} ${res.statusText}`);
}
const text = await res.text();
const data = safeJson(text);
if (data instanceof Error) {
throw new Error(`Could not process API response. text=${text} data=${data} status=${res.status}`);
}
console.log('API Response', data);
if (data?.error) {
throw new Error(`API Error ${res.status} - ${data.error}`);
}
if (!res.ok) {
throw new Error(`API Error ${res.status} - ${data}`);
}
if (data?.token) {
return { token: data.token };
}
}
/**
* Returns an `Error` object if parsing the given JSON string fails instead of throwing
*/
function safeJson(input) {
try {
return JSON.parse(input);
} catch (err) {
return new Error(err);
}
}
main();