-
Notifications
You must be signed in to change notification settings - Fork 19
/
webviewApi.ts
95 lines (79 loc) · 2.74 KB
/
webviewApi.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
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
import { container } from 'tsyringe';
import { EventEmitter } from 'eventemitter3';
import { cloneDeep } from 'lodash';
import { GithubClient, GithubClientEvents, githubClientToken } from 'domain/service/PublishService';
import { Github as GithubInfo, PublishError, PublishResults } from 'domain/model/Publishing';
export class Github extends EventEmitter<GithubClientEvents> implements GithubClient {
private githubInfo?: GithubInfo;
private async request(method: 'GET' | 'POST', path: string, payload?: Record<string, string>) {
if (!this.githubInfo?.token) {
throw new Error('no github info');
}
const response = await fetch(
`https://api.github.com${path}${
method === 'GET' && payload ? `?${new URLSearchParams(payload).toString()}` : ''
}`,
{
method,
headers: {
Accept: 'application/vnd.github.v3+json',
Authorization: `token ${this.githubInfo.token}`,
'User-Agent': 'Joplin Pages Publisher',
...(method === 'POST' ? { 'Content-Type': 'application/json' } : null),
},
body: method === 'POST' && payload ? JSON.stringify(payload) : null,
},
);
return response.ok ? response.json() : Promise.reject(response.status);
}
getRepositoryName() {
if (!this.githubInfo) {
throw new Error('no github info');
}
return this.githubInfo.repositoryName || this.getDefaultRepositoryName();
}
getDefaultRepositoryName() {
if (!this.githubInfo?.userName) {
throw new Error('no github info');
}
return `${this.githubInfo.userName}.github.io`;
}
init(githubInfo: GithubInfo) {
const oldGithubInfo = this.githubInfo;
this.githubInfo = cloneDeep(githubInfo);
if (
oldGithubInfo?.userName === githubInfo.userName &&
oldGithubInfo?.token === githubInfo.token &&
(oldGithubInfo?.repositoryName || '') === (githubInfo.repositoryName || '')
) {
return;
}
this.emit(GithubClientEvents.InfoChanged, githubInfo);
this.githubInfo = githubInfo;
}
async createRepository() {
try {
await this.request('POST', '/user/repos', {
name: this.getRepositoryName(),
description: 'Blog Website By Joplin Pages Publisher',
});
} catch (error) {
throw new PublishError(PublishResults.Fail, error);
}
}
getGithubInfo() {
if (!this.githubInfo) {
throw new Error('no github info');
}
return this.githubInfo;
}
getRepositoryUrl() {
if (!this.githubInfo) {
throw new Error('no github info');
}
const { userName } = this.githubInfo;
const repoName = this.getRepositoryName();
return `https://github.com/${userName}/${repoName}.git`;
}
}
container.registerSingleton(githubClientToken, Github);