gengitkan/client/src/util/gitea.ts

85 lines
2.2 KiB
TypeScript
Raw Normal View History

2019-12-01 22:12:13 +01:00
export class GiteaUnauthorizedError extends Error {
2020-04-30 13:02:56 +02:00
constructor(...args: any[]) {
2019-12-01 22:12:13 +01:00
super(...args)
2020-05-06 11:30:26 +02:00
Object.setPrototypeOf(this, GiteaUnauthorizedError.prototype);
2019-12-01 22:12:13 +01:00
}
}
2019-11-28 14:12:48 +01:00
export class GiteaClient {
2020-04-30 13:02:56 +02:00
fetchIssues(project: any, page = 1) {
2019-12-05 14:44:33 +01:00
return fetch(`/gitea/api/v1/repos/${project}/issues?page=${page}`)
2019-12-01 22:12:13 +01:00
.then(this.assertAuthorization)
2019-12-06 17:15:18 +01:00
.then(this.assertOk)
2019-12-01 22:12:13 +01:00
.then(res => res.json())
;
}
fetchUserProjects(page = 1) {
return fetch(`/gitea/api/v1/user/repos?page=${page}`)
2019-12-01 22:12:13 +01:00
.then(this.assertAuthorization)
2019-12-06 17:15:18 +01:00
.then(this.assertOk)
2019-12-01 22:12:13 +01:00
.then(res => res.json())
;
}
2020-04-30 13:02:56 +02:00
addIssueLabel(project: any, issueNumber: any, labelID: any) {
2019-12-01 22:12:13 +01:00
return fetch(`/gitea/api/v1/repos/${project}/issues/${issueNumber}/labels`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ labels: [labelID] }),
})
.then(this.assertAuthorization)
2019-12-06 17:15:18 +01:00
.then(this.assertOk)
2019-12-01 22:12:13 +01:00
.then(res => res.json())
}
2020-04-30 13:02:56 +02:00
fetchProjectLabels(project: any) {
2019-12-01 22:12:13 +01:00
return fetch(`/gitea/api/v1/repos/${project}/labels`)
.then(this.assertAuthorization)
2019-12-06 17:15:18 +01:00
.then(this.assertOk)
2019-12-01 22:12:13 +01:00
.then(res => res.json())
;
}
2020-04-30 13:02:56 +02:00
removeIssueLabel(project: any, issueNumber: any, labelID: any) {
2019-12-01 22:12:13 +01:00
return fetch(`/gitea/api/v1/repos/${project}/issues/${issueNumber}/labels/${labelID}`, {
method: 'DELETE'
})
.then(this.assertAuthorization)
2019-12-06 17:15:18 +01:00
.then(this.assertOk)
2019-12-01 22:12:13 +01:00
}
2020-04-30 13:02:56 +02:00
createIssue(project: any, title: any, body: any, labelID: any) {
2019-12-05 22:37:09 +01:00
return fetch(`/gitea/api/v1/repos/${project}/issues`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title,
body,
labels: labelID ? [labelID] : undefined,
2019-12-05 22:37:09 +01:00
}),
})
.then(this.assertAuthorization)
2019-12-06 17:15:18 +01:00
.then(this.assertOk)
2019-12-05 22:37:09 +01:00
.then(res => res.json())
}
2020-04-30 13:02:56 +02:00
assertOk(res: any) {
2019-12-01 22:12:13 +01:00
if (!res.ok) return Promise.reject(new Error('Request failed'));
return res;
}
2020-04-30 13:02:56 +02:00
assertAuthorization(res: any) {
2019-12-01 22:12:13 +01:00
if (res.status === 401 || res.status === 404) return Promise.reject(new GiteaUnauthorizedError());
return res;
2019-11-28 14:12:48 +01:00
}
}
export const gitea = new GiteaClient();