-
Notifications
You must be signed in to change notification settings - Fork 4
/
api.ts
313 lines (293 loc) · 9.47 KB
/
api.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import type {
AccessToken,
Account,
AuthUrl,
Node,
Page,
PageCount,
PageList,
PageViews,
} from "./types.ts";
const API_ROOT = "https://api.telegra.ph";
interface Options {
/** Access token of the Telegraph account */
token?: string;
/** Root URL of the API server. Defaults to https://telegra.ph/api. */
apiRoot?: string;
}
/** All account fields that is returned by `getAccount` method. */
export const ACCOUNT_FIELDS = [
"short_name",
"author_name",
"author_url",
"auth_url",
"page_count",
] as const;
/** Account fields that can be requested through `getAccountInfo` method. */
export type AccountFields = typeof ACCOUNT_FIELDS[number];
/**
* Error handler that can be installed on a Telegraph instance to catch error
* thrown by the API calls.
*/
export type ErrorHandler = (error?: unknown) => unknown;
/**
* Most important class of the module. Helps to manage accounts and created
* Telegraph pages.
*/
export class Telegraph {
/**
* Holds the error handler of the instance that is invoked whenever API calls
* (rejects). If you set your own error handler via `t.catch`, all that
* happens is that this variable is assigned.
*/
public errorHandler: ErrorHandler = (err) => {
console.error("No error handler was set!");
console.error("Set your own error handler with `.catch((err) => ...)`");
console.error(err);
throw err;
};
/**
* Sets the instance's error handler that is called whenever an error occurs.
*
* @param errorHandler A function that handles potential errors
*/
catch(errorHandler: ErrorHandler): void {
this.errorHandler = errorHandler;
}
constructor(
/** Options for configuring the instance */
private options: Options = {},
) {
options.apiRoot ??= API_ROOT;
}
/** Access token of the instance */
get token(): string | undefined {
return this.options.token;
}
set token(token: string) {
this.options.token = token;
}
// deno-lint-ignore no-explicit-any
async #request<T>(method: string, body?: T): Promise<any> {
const url = `${this.options.apiRoot}/${method}`;
let response: Response;
try {
response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ access_token: this.token, ...body }),
});
} catch (err) {
return await this.errorHandler(err);
}
if (!response.ok) {
return await this.errorHandler(`Request failed: ${response.statusText}`);
}
const json = await response.json();
if (!json.ok) return await this.errorHandler(json.error);
return json.result;
}
/**
* Use this method to create a new Telegraph account. Most users only need
* one account, but this can be useful for channel administrators who would
* like to keep individual author names and profile links for each of their
* channels.
*
* @param details Details of the account.
*
* @returns On success, returns an Account object with the regular fields
* and an additional access_token field.
*/
createAccount(details: {
/**
* Account name, helps users with several accounts remember which they are
* currently using. Displayed to the user above the "Edit/Publish" button
* on Telegra.ph, other users don't see this name.
*/
short_name: string;
/** Default author name used when creating new articles. */
author_name?: string;
/**
* Default profile link, opened when users click on the author's name below
* the title. Can be any link, not necessarily to a Telegram profile or
* channel.
*/
author_url?: string;
}): Promise<Account & AccessToken & AuthUrl> {
return this.#request("createAccount", details);
}
/**
* Use this method to get information about a Telegraph account.
*
* @param fields List of account fields to return. Defaults to all
* (`short_name`, `author_name`, `author_url`, `auth_url`, and `page_count`).
*
* @returns Account object on success.
*/
getAccount<K extends AccountFields>(
fields?: K[],
): Promise<{ [key in K]: Required<Account & AuthUrl & PageCount>[key] }> {
return this.#request("getAccountInfo", {
fields: fields ?? ACCOUNT_FIELDS,
});
}
/**
* Use this method to update information about a Telegraph account. Pass only
* the parameters that you want to edit.
*
* @param details Details of the account
*
* @returns On success, returns an Account object with the default fields.
*/
editAccount(details: {
/** New account name. */
short_name?: string;
/** New default author name used when creating new articles. */
author_name?: string;
/**
* New default profile link, opened when users click on the author's name
* below the title. Can be any link, not necessarily to a Telegram profile
* or channel.
*/
author_url?: string;
}): Promise<Account> {
return this.#request("editAccountInfo", details);
}
/**
* Use this method to revoke access_token and generate a new one, for example,
* if the user would like to reset all connected sessions, or you have reasons
* to believe the token was compromised.
*
* @param options Options for the method.
*
* @returns On success, returns an Account object with new access_token and
* auth_url fields.
*/
async revokeToken(options = {
/** Whether to apply the new access token to the instance. */
save: true,
}): Promise<AccessToken & AuthUrl> {
const creds = await this.#request("revokeAccessToken");
if (creds && options.save) this.token = creds.access_token;
return creds;
}
/**
* Use this method to create a new Telegraph page.
*
* @param options Information about the page.
*
* @returns On success, returns a Page object.
*/
create<T extends boolean>(
options: {
/** Page title. */
title: string;
/** Content of the page. */
content: string | Node[];
/** Author name, displayed below the article's title. */
author_name?: string;
/**
* Profile link, opened when users click on the author's name below the
* title. Can be any link, not necessarily to a Telegram profile or channel.
*/
author_url?: string;
/** If true, a content field will be returned in the Page object. */
return_content?: T;
},
): Promise<Page<T>> {
return this.#request("createPage", {
...options,
content: typeof options.content === "string"
? [options.content]
: options.content,
});
}
/**
* Use this method to edit an existing Telegraph page.
*
* @param path Path to the page.
* @param options Details to edit the page.
*
* @returns On success, returns a Page object.
*/
edit<T extends boolean>(
path: string,
options: {
/** Page title. */
title: string;
/** Content of the page. */
content: string | Node[];
/** Author name, displayed below the article's title. */
author_name?: string;
/**
* Profile link, opened when users click on the author's name below the
* title. Can be any link, not necessarily to a Telegram profile or channel.
*/
author_url?: string;
/** If true, a content field will be returned in the Page object. */
return_content?: T;
},
): Promise<Page<T>> {
return this.#request("editPage", { path, ...options });
}
/**
* Use this method to get a Telegraph page.
*
* @param path Path to the Telegraph page (in the format Title-12-31, i.e. everything that comes after http://telegra.ph/).
* @param options Additional parameters.
*
* @returns Returns a Page object on success.
*/
get(path: string, options = {
/** If true, content field will be returned in Page object. Defaults to true. */
return_content: true,
}): Promise<Page<true>> {
return this.#request("getPage", { path, ...options });
}
/**
* Use this method to get a list of pages belonging to a Telegraph account.
*
* @param options Additional parameters.
*
* @returns Returns a PageList object, sorted by most recently created pages first.
*/
getPages(options?: {
/** Sequential number of the first page to be returned. */
offset?: number;
/** Limits the number of pages to be retrieved. */
limit?: number;
}): Promise<PageList> {
return this.#request("getPageList", options);
}
/**
* Use this method to get the number of views for a Telegraph article.
*
* @param path Path to the Telegraph page (in the format Title-12-31, where 12
* is the month and 31 the day the article was first published).
* @param options Additional parameters to get views gained in a specific time
* period.
*
* @returns Returns a PageViews object on success. By default, the total number of page views will be returned.
*/
getViews(path: string, options?: {
/**
* Required if month is passed. If passed, the number of page views for the
* requested year will be returned.
*/
year?: number;
/**
* Required if day is passed. If passed, the number of page views for the
* requested month will be returned.
*/
month?: number;
/**
* Required if hour is passed. If passed, the number of page views for the
* requested day will be returned.
*/
day?: number;
/** If passed, the number of page views for the requested hour will be returned. */
hour?: number;
}): Promise<PageViews> {
return this.#request("getViews", { path, ...options });
}
}