-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkflow.js
92 lines (90 loc) · 2.13 KB
/
workflow.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
89
90
91
92
const http = require("http");
const https = require("https");
const querystring = require("querystring");
const path = require("path");
const fs = require("fs");
const db = path.resolve(__dirname, "db.json");
class Flow {
constructor() {
this.argv = process.argv[2];
}
log(items) {
console.log(JSON.stringify({items}));
}
request(url, data = {}, opt = {}) {
return new Promise((resolve, reject) => {
let protocol = http;
if (url.indexOf("https") > -1) {
protocol = https;
}
let req = protocol.request(url, opt, (res) => {
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
resolve(rawData, res);
});
}).on('error', (err) => {
reject(err);
});
req.write(querystring.stringify(data));
req.end();
});
}
get(url, data = {}, opt = {}) {
url += "?" + querystring.stringify(data);
return this.request(url, {}, {
method: "GET"
});
}
post(url, data = {}, opt = {}) {
opt.method = "POST";
return this.request(url, data, opt);
}
icon(img) {
return {
path: path.resolve(__dirname, img)
};
}
getItem(key) {
return new Promise((resolve, reject) => {
fs.stat(db, (err, stats) => {
if (!err) {
let str = fs.readFileSync(db).toString();
try {
let data = JSON.parse(str);
resolve(data[key]);
} catch(e) {
resolve();
}
} else {
reject(err);
}
});
})
}
setItem(key, value) {
return new Promise((resolve, reject) => {
let data;
fs.stat(db, (err, stats) => {
if (!err) {
let str = fs.readFileSync(db);
try {
data = JSON.parse(str);
} catch(e) {
data = {};
}
}
data[key] = value;
data = JSON.stringify(data, null, "\t");
fs.writeFile(db, data, (err) => {
if (err) {
resolve(false);
} else {
resolve(true);
}
});
});
});
}
}
module.exports = Flow;