gitlab/ts/gitlab.classes.account.ts
2021-05-16 23:59:47 +00:00

65 lines
1.9 KiB
TypeScript

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
*/
public async request(
methodArg: 'GET' | 'POST',
routeArg: string,
searchParamsArg: { [key: string]: string }
) {
if (!routeArg.startsWith('/')) {
throw new Error(`"${routeArg}" -> routeArg must start with a slash`);
}
const smarturlInstance = plugins.smarturl.Smarturl.createFromUrl(
`https://gitlab.com/api/v4${routeArg}`,
{
searchParams: searchParamsArg,
}
);
const response = await plugins.smartrequest.request(smarturlInstance.toString(), {
method: methodArg,
});
// lets deal with pagination headers
const findLinkName = (markup) => {
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;
}[] = [];
for (const link of links) {
linkObjects.push({
original: link,
link: findLinkName(link),
});
}
const next = linkObjects.find((linkObject) => linkObject.original.includes('rel="next"'));
if (next && response.body instanceof Array) {
const nextResponse = await this.request(
methodArg,
next.link.replace('https://gitlab.com/api/v4', ''),
{}
);
response.body = response.body.concat(nextResponse);
}
}
return response.body;
}
}