This repository was archived by the owner on Feb 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
64 lines (56 loc) · 1.46 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
// Core modules
var http = require("http");
var request = require("request");
var base64 = require("base-64");
var rp = require("request-promise");
// Event module
var events = require("events");
class HarperDB {
constructor() {
this.options = {};
this.isConnected = false;
this.event = new events.EventEmitter();
}
connect(url, username, password) {
if (arguments.length !== 3)
throw new Error("Connect must be passed 3 arguments");
else if (
typeof url !== "string" ||
typeof username !== "string" ||
typeof password !== "string"
)
throw new Error("connect() arguments must be strings");
const authorization = `Basic ${base64.encode(`${username}:${password}`)}`;
const options = {
method: "POST",
url,
headers: {
"content-type": "application/json",
authorization
},
json: true
};
return rp({
...options,
body: { operation: "list_users" }
})
.then(() => {
this.event.emit("connection");
this.isConnected = true;
this.options = options;
})
.catch(error => {
this.event.emit("error", error);
});
}
request(query) {
if (!this.isConnected) {
this.event.emit("error");
throw new Error("Must connect to DB first using .connect()");
} else {
this.event.emit("request");
return rp({ ...this.options, body: query });
}
}
}
module.exports.HarperDB = HarperDB;