-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (72 loc) · 2.47 KB
/
index.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
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
const https = require("https");
class hastebin {
/**
* Initiate client.
* @param {Object} config Client config
* @param {string} [config.server] HasteBin server (defaults to https://hastebin.com/)
* @returns {null}
*/
constructor(config) {
this.server = (config || {}).server || "https://hastebin.com/";
if (!this.server.endsWith("/")) this.server = `${this.server}/`;
this.base = this.server.split("//")[1];
this.base = this.base.substring(0, this.base.length - 1);
};
/**
* Read a haste.
* @param {string} key Haste key
* @returns {Promise.<String>} Haste data (content)
*/
read(key) {
return new Promise((promiseRes, promiseRej) => {
if (!key) promiseRej("Argument 1 missing or null.");
https.get(`${this.server}documents/${key}`, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
const json = JSON.parse(data);
if (res.statusCode === 200) {
promiseRes(json.data);
} else if (res.statusCode === 404) {
promiseRej(`${json.message} (${res.statusCode})`);
} else {
promiseRej(`${res.statusMessage} (${res.statusCode})`);
};
});
});
});
};
/**
* Create/write a haste.
* @param {string} text Haste data (content)
* @returns {Promise.<String>} Haste key
*/
write(text) {
return new Promise((promiseRes, promiseRej) => {
if (!text) promiseRej("Argument 1 missing or null.");
const req = https.request({
"hostname": this.base,
"path": "/documents",
"headers": {
"Content-Type": "text/plain",
"Content-Length": text.length
},
"method": "POST"
}, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
const json = JSON.parse(data);
promiseRes(json.key);
});
});
req.write(text);
req.end();
});
};
};
module.exports = hastebin;