-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkflow.js
126 lines (124 loc) · 2.99 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
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
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.headers = {};
let obj = {};
process.argv.forEach((item, i) => {
if (item.indexOf("--") === 0) {
item = item.substring(2);
if (item.indexOf("=") > -1) {
let arr = item.split("=");
let key = arr[0];
let value = arr[1];
obj[key] = value;
} else {
obj[item] = true;
}
} else if (i > 1) {
this.input = process.argv[i];
}
});
this.argv = obj;
}
log(items) {
if (typeof items === "string") {
console.log(JSON.stringify({items: [{
title: items
}]}));
} else {
console.log(JSON.stringify({items}));
}
}
icon(img) {
return {
path: path.resolve(__dirname, img)
};
}
setHeader(headers) {
this.headers = headers;
}
request(url, data = {}, opt = {}) {
return new Promise((resolve, reject) => {
let protocol = http;
if (url.indexOf("https") > -1) {
protocol = https;
}
opt = Object.assign({headers: this.headers}, opt);
console.error(opt);
let req = protocol.request(url, opt, (res) => {
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
res.data = rawData;
resolve(res);
});
}).on('error', (err) => {
reject(err);
});
req.write(JSON.stringify(data));
req.end();
});
}
get(url, data = {}, opt = {}) {
data = querystring.stringify(data);
url = data ? url + "?" + data : url;
opt.method = "GET";
return this.request(url, {}, opt);
}
post(url, data = {}, opt = {}) {
Object.assign(opt, {
method: "POST",
headers: {
"Content-Type": "application/json;charset=UTF-8",
}
});
return this.request(url, data, opt);
}
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 {
resolve();
}
});
})
}
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[key] = value;
data = JSON.stringify(data, null, "\t");
fs.writeFile(db, data, (err) => {
console.error(err);
if (err) {
resolve(false);
} else {
resolve(true);
}
});
});
});
}
}
module.exports = Flow;