/
gitea.ts
67 lines (56 loc) · 1.8 KB
/
gitea.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
import url from 'url';
import { PLATFORM_TYPE_GITEA } from '../../constants/platforms';
import { Http, HttpOptions, HttpResponse, InternalHttpOptions } from '.';
let baseUrl;
export const setBaseUrl = (newBaseUrl: string): void => {
baseUrl = newBaseUrl.replace(/\/*$/, '/');
};
export interface GiteaHttpOptions extends InternalHttpOptions {
paginate?: boolean;
token?: string;
}
function getPaginationContainer(body: any): any[] {
if (Array.isArray(body) && body.length) {
return body;
}
if (Array.isArray(body?.data) && body.data.length) {
return body.data;
}
return null;
}
function resolveUrl(path: string): URL {
const resolvedUrlString = url.resolve(baseUrl, path);
return new url.URL(resolvedUrlString);
}
export class GiteaHttp extends Http<GiteaHttpOptions, GiteaHttpOptions> {
constructor(options?: HttpOptions) {
super(PLATFORM_TYPE_GITEA, options);
}
protected async request<T>(
path: string,
options?: InternalHttpOptions & GiteaHttpOptions
): Promise<HttpResponse<T> | null> {
const resolvedUrl = resolveUrl(path);
const opts = {
baseUrl,
...options,
};
const res = await super.request<T>(resolvedUrl, opts);
const pc = getPaginationContainer(res.body);
if (opts.paginate && pc) {
const total = parseInt(res.headers['x-total-count'] as string, 10);
let nextPage = parseInt(resolvedUrl.searchParams.get('page') || '1', 10);
while (total && pc.length < total) {
nextPage += 1;
resolvedUrl.searchParams.set('page', nextPage.toString());
const nextRes = await super.request<T>(resolvedUrl.toString(), opts);
const nextPc = getPaginationContainer(nextRes.body);
if (nextPc === null) {
break;
}
pc.push(...nextPc);
}
}
return res;
}
}