-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiClient.ts
72 lines (64 loc) · 1.73 KB
/
ApiClient.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
import fs from 'fs';
import fetch, { BodyInit } from 'node-fetch';
export type AnalysisRequestRequest = {
benchmarkName: string
apkId?: string
instrumentationApkId?: string
iosAppBinaryId?: string
repoOwner?: string
repoName?: string
pullRequestId?: string
branch?: string
analysisIds?: string[]
targetId?: string
}
export default class ApiClient {
constructor(
private apiKey: string,
private apiUrl: string
) { }
async uploadApp(appFile: string, path: string) {
return await this.uploadFile(appFile, path)
}
async uploadMapping(mappingFile: string, apkId: string) {
return await this.uploadFile(mappingFile, `mapping/${apkId}`)
}
async createAnalysisRequest(body: AnalysisRequestRequest) {
return await this.apiRequest({
method: 'POST',
path: 'analysis',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
})
}
private async uploadFile(file: string, path: string) {
const fileStream = fs.createReadStream(file);
const fileSize = fs.statSync(file).size;
return await this.apiRequest({
method: 'POST',
path,
headers: { 'Content-Length': `${fileSize}` },
body: fileStream
});
}
private async apiRequest({ method, path, headers, body }: {
method: string,
path: string,
headers?: HeadersInit,
body?: BodyInit | null
}): Promise<any> {
const res = await fetch(`${this.apiUrl}/${path}`, {
method,
headers: {
'Authorization': `Bearer ${this.apiKey}`,
...headers
},
body
});
if (!res.ok) {
const body = await res.text();
throw new Error(`Request to ${res.url} failed (${res.status}): ${body}`);
}
return await res.json();
}
}