-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.js
62 lines (52 loc) · 1.59 KB
/
api.js
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
"use strict";
/* Did anyone ask for a homebrew Mediawiki API implementation? No? Well you're
* getting one anyway. */
class MediawikiError extends Error {
constructor(code, info) {
super(`${code}: ${info}`);
this.name = "MediawikiError";
this.code = code;
this.info = info;
}
}
class API {
constructor(endpoint) {
this.endpoint = endpoint;
}
processOptions(options) {
options = {
...options,
format: "json",
formatversion: 2,
origin: "*",
};
for (let key in options) {
if (Array.isArray(options[key])) {
options[key] = "\x1F" + options[key].join("\x1F");
} else if (options[key] === undefined) {
delete options[key];
}
}
return options;
}
async get(options) {
options = this.processOptions(options);
let search = new URLSearchParams(options);
let resp = await fetch(`${this.endpoint}?${search.toString()}`);
let data = await resp.json();
if (data.error) {
throw new MediawikiError(data.error.code, data.error.info);
}
return data;
}
async post(options) {
options = this.processOptions(options);
let search = new URLSearchParams(options);
let resp = await fetch(new Request(this.endpoint, {method: "POST", body: search}));
let data = await resp.json();
if (data.error) {
throw new MediawikiError(data.error.code, data.error.info);
}
return data;
}
}