gitlab/ts/gitlab.classes.account.ts

65 lines
1.9 KiB
TypeScript
Raw Normal View History

2021-05-16 12:16:35 +00:00
import { GitlabGroup } from './gitlab.classes.group';
import * as plugins from './gitlab.plugins';
export class GitlabAccount {
public static createAnonymousAccount() {
return new GitlabAccount();
}
// INSTANCE
public async getGroupByName(nameArg: string): Promise<GitlabGroup> {
return GitlabGroup.getByName(nameArg, this);
}
/**
* handles the basic request/response patterns with the gitlab.com API
*/
2021-05-16 23:50:56 +00:00
public async request(
methodArg: 'GET' | 'POST',
routeArg: string,
searchParamsArg: { [key: string]: string }
) {
if (!routeArg.startsWith('/')) {
2021-05-16 12:16:35 +00:00
throw new Error(`"${routeArg}" -> routeArg must start with a slash`);
}
2021-05-16 23:50:56 +00:00
const smarturlInstance = plugins.smarturl.Smarturl.createFromUrl(
`https://gitlab.com/api/v4${routeArg}`,
{
searchParams: searchParamsArg,
}
);
2021-05-16 12:16:35 +00:00
const response = await plugins.smartrequest.request(smarturlInstance.toString(), {
2021-05-16 23:50:56 +00:00
method: methodArg,
2021-05-16 12:16:35 +00:00
});
// lets deal with pagination headers
2021-05-16 23:50:56 +00:00
const findLinkName = (markup) => {
2021-05-16 12:16:35 +00:00
const pattern = /<([^\s>]+)(\s|>)+/;
return markup.match(pattern)[1];
};
if (typeof response.headers.link === 'string') {
const links = response.headers.link.split(',');
const linkObjects: {
original: string;
link: string;
}[] = [];
2021-05-16 23:50:56 +00:00
for (const link of links) {
linkObjects.push({
original: link,
2021-05-16 23:59:47 +00:00
link: findLinkName(link),
2021-05-16 23:50:56 +00:00
});
}
2021-05-16 23:59:47 +00:00
const next = linkObjects.find((linkObject) => linkObject.original.includes('rel="next"'));
2021-05-16 23:50:56 +00:00
if (next && response.body instanceof Array) {
2021-05-16 23:59:47 +00:00
const nextResponse = await this.request(
methodArg,
next.link.replace('https://gitlab.com/api/v4', ''),
{}
);
2021-05-16 23:50:56 +00:00
response.body = response.body.concat(nextResponse);
}
2021-05-16 12:16:35 +00:00
}
return response.body;
}
}