-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapi.ts
More file actions
181 lines (158 loc) · 4.53 KB
/
api.ts
File metadata and controls
181 lines (158 loc) · 4.53 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
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
import fs from 'fs';
import path from 'path';
import util from 'util';
import filesizeParser from 'filesize-parser';
import FormData from 'form-data';
import fetch from 'node-fetch';
import ProgressBar from 'progress';
import tcpp from 'tcp-ping';
import { getBaseUrl } from 'utils/http-helper';
import packageJson from '../package.json';
import type { Package, Session } from './types';
import { credentialFile, pricingPageUrl } from './utils/constants';
import { t } from './utils/i18n';
const tcpPing = util.promisify(tcpp.ping);
let session: Session | undefined;
let savedSession: Session | undefined;
const userAgent = `react-native-update-cli/${packageJson.version}`;
export const getSession = () => session;
export const replaceSession = (newSession: { token: string }) => {
session = newSession;
};
export const loadSession = async () => {
if (fs.existsSync(credentialFile)) {
try {
replaceSession(JSON.parse(fs.readFileSync(credentialFile, 'utf8')));
savedSession = session;
} catch (e) {
console.error(
`Failed to parse file ${credentialFile}. Try to remove it manually.`,
);
throw e;
}
}
};
export const saveSession = () => {
// Only save on change.
if (session !== savedSession) {
const current = session;
const data = JSON.stringify(current, null, 4);
fs.writeFileSync(credentialFile, data, 'utf8');
savedSession = current;
}
};
export const closeSession = () => {
if (fs.existsSync(credentialFile)) {
fs.unlinkSync(credentialFile);
savedSession = undefined;
}
session = undefined;
};
async function query(url: string, options: fetch.RequestInit) {
const baseUrl = await getBaseUrl;
const fullUrl = `${baseUrl}${url}`;
const resp = await fetch(fullUrl, options);
const text = await resp.text();
let json: any;
try {
json = JSON.parse(text);
} catch (e) {}
if (resp.status !== 200) {
const message = json?.message || resp.statusText;
if (resp.status === 401) {
throw new Error(t('loginExpired'));
}
throw new Error(message);
}
return json;
}
function queryWithoutBody(method: string) {
return (api: string) =>
query(api, {
method,
headers: {
'User-Agent': userAgent,
'X-AccessToken': session ? session.token : '',
},
});
}
function queryWithBody(method: string) {
return (api: string, body?: Record<string, any>) =>
query(api, {
method,
headers: {
'User-Agent': userAgent,
'Content-Type': 'application/json',
'X-AccessToken': session ? session.token : '',
},
body: JSON.stringify(body),
});
}
export const get = queryWithoutBody('GET');
export const post = queryWithBody('POST');
export const put = queryWithBody('PUT');
export const doDelete = queryWithBody('DELETE');
export async function uploadFile(fn: string, key?: string) {
const { url, backupUrl, formData, maxSize } = await post('/upload', {
ext: path.extname(fn),
});
let realUrl = url;
if (backupUrl) {
// @ts-ignore
if (global.USE_ACC_OSS) {
realUrl = backupUrl;
} else {
const pingResult = await tcpPing({
address: url.replace('https://', ''),
attempts: 4,
timeout: 1000,
});
// console.log({pingResult});
if (Number.isNaN(pingResult.avg) || pingResult.avg > 150) {
realUrl = backupUrl;
}
}
// console.log({realUrl});
}
const fileSize = fs.statSync(fn).size;
if (maxSize && fileSize > filesizeParser(maxSize)) {
const readableFileSize = `${(fileSize / 1048576).toFixed(1)}m`;
throw new Error(
t('fileSizeExceeded', {
fileSize: readableFileSize,
maxSize,
pricingPageUrl,
}),
);
}
const bar = new ProgressBar(' Uploading [:bar] :percent :etas', {
complete: '=',
incomplete: ' ',
total: fileSize,
});
const form = new FormData();
for (const [k, v] of Object.entries(formData)) {
form.append(k, v);
}
const fileStream = fs.createReadStream(fn);
fileStream.on('data', (data) => {
bar.tick(data.length);
});
if (key) {
form.append('key', key);
}
form.append('file', fileStream);
const res = await fetch(realUrl, {
method: 'POST',
body: form,
});
if (res.status > 299) {
throw new Error(`${res.status}: ${res.statusText}`);
}
// const body = await response.json();
return { hash: key || formData.key };
}
export const getAllPackages = async (appId: string) => {
const { data } = await get(`/app/${appId}/package/list?limit=1000`);
return data as Package[] | undefined | null;
};