forked from opencoconut/coconutjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coconut.js
103 lines (86 loc) · 2.56 KB
/
coconut.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
var assert = require('assert');
var http = require('http');
var https = require('https');
var url = require('url');
var fs = require('fs');
var USER_AGENT = 'Coconut/2.2.0 (NodeJS)';
module.exports = {
submit: function(configContent, apiKey, callback) {
coconutURL = url.parse(process.env.HEYWATCH_URL || 'https://api.coconut.co');
if(!apiKey) {
apiKey = process.env.COCONUT_API_KEY;
}
var reqOptions = {
hostname: coconutURL.hostname,
port: coconutURL.port || (coconutURL.protocol == 'https:' ? 443 : 80),
path: '/v1/job',
method: 'POST',
auth: apiKey+':',
headers: {
'User-Agent': USER_AGENT,
'Content-Type': 'text/plain',
'Accept': 'application/json',
'Content-Length': configContent.length
}
};
var req = (coconutURL.protocol == 'https:' ? https : http).request(reqOptions, function(res) {
res.setEncoding('utf8');
var responseString = '';
res.on('data', function(data) {
responseString += data;
});
res.on('end', function () {
var resultObject = JSON.parse(responseString);
if(callback) {
callback(resultObject);
}
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
if(callback) {
callback(null);
}
});
req.write(configContent);
req.end();
},
config: function(options) {
conf_file = options.conf;
if(conf_file) {
conf = fs.readFileSync(conf_file, 'utf8').split("\n");
} else {
conf = [];
}
vars = options.vars;
if(vars) {
for(v in vars) {
conf.push('var ' + v + ' = ' + String(vars[v]));
}
}
source = options.source;
if(source) {
conf.push('set source = ' + source);
}
webhook = options.webhook;
if(webhook) {
conf.push('set webhook = ' + webhook);
}
outputs = options.outputs;
if(outputs) {
for(format in outputs) {
conf.push('-> ' + format + ' = ' + String(outputs[format]));
}
}
new_conf = [];
new_conf = new_conf.concat(conf.filter(function(l) { return l.indexOf('var') === 0 } ).sort());
new_conf.push('');
new_conf = new_conf.concat(conf.filter(function(l) { return l.indexOf('set') === 0 } ).sort());
new_conf.push('');
new_conf = new_conf.concat(conf.filter(function(l) { return l.indexOf('->') === 0 } ).sort());
return new_conf.join('\n');
},
createJob: function(options, callback) {
this.submit(this.config(options), options.api_key, callback);
}
}