-
Notifications
You must be signed in to change notification settings - Fork 30
/
sdk.ts
88 lines (80 loc) · 2.02 KB
/
sdk.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
import {
LinkPageAuthorParams,
PageResult,
RequestProps,
type Project,
type User,
} from './types';
export class ChirpySDK {
constructor(
private apiKey: string,
private origin: string = 'https://chirpy.dev',
) {}
public getProject(domain: string): Promise<Project | null> {
return this.request({ path: '/api/sdk/project', searchParams: { domain } });
}
public createProject(domain: string, name: string): Promise<Project> {
return this.request({
path: '/api/sdk/project',
body: { domain, name },
method: 'POST',
});
}
public deleteProject(domain: string): Promise<void> {
return this.request({
path: '/api/sdk/project',
searchParams: { domain },
method: 'DELETE',
});
}
public getPage(url: string): Promise<PageResult | null> {
return this.request({ path: '/api/sdk/page', searchParams: { url } });
}
public linkPageAuthor(params: LinkPageAuthorParams): Promise<void> {
return this.request({
path: '/api/sdk/page/link-author',
body: params,
method: 'POST',
});
}
public createUser(email: string, name: string): Promise<User> {
return this.request({
path: '/api/sdk/user',
body: {
email,
name,
},
method: 'POST',
});
}
private async request({
path,
body,
searchParams,
method = 'GET',
}: RequestProps) {
const url = new URL(`${this.origin}${path}`);
Object.entries(searchParams || {}).forEach(([key, value]) => {
url.searchParams.set(key, value);
});
const res = await fetch(url.href, {
headers: {
authorization: `Bearer ${this.apiKey}`,
},
method,
body: body ? JSON.stringify(body) : undefined,
});
if (!res.ok) {
throw new Error(
`Chirpy SDK API Error:\nstatus:${res.status}\n${await res.text()}`,
);
}
try {
const data = await res.json();
return data;
} catch {
// ignore, no json response
console.log(`No JSON response`);
}
}
}