-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
73 lines (58 loc) · 1.74 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
'use strict';
const bodyParser = require('body-parser')
const express = require('express')
const app = express()
app.set('port', 8080)
app.use(bodyParser.json())
const server = app.listen(app.get('port'), function() {
const host = server.address().address;
const port = server.address().port;
console.log('[start] listening at http://%s:%s', host, port);
});
const run_req = (req, res) => {
console.log('openwhisk invoke request: ', req.body)
const args = req.body.value
invoke_jq(args).then(result => {
res.json(result)
}).catch(err => {
res.status(500).json({error: err});
})
}
app.post('/init', (req, res) => res.send())
app.post('/run', run_req);
const invoke_jq = params => {
if (!params.jq) {
return Promise.reject('Missing jq parameter.')
}
const filter = params.jq
delete params.jq
return jq(JSON.stringify(params), filter).then(result => JSON.parse(result))
}
const jq = (stdin, filter) => {
return new Promise((resolve, reject) => {
const spawn = require('child_process').spawn;
const process = spawn('jq', [filter]);
const output = []
process.stdout.on('data', (data) => {
output.push(data)
});
process.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
process.on('exit', (code, signal) => {
if (code !== 0) {
return reject('jq command failed, invalid input or filter?');
}
console.log(`stdout: ${output.join('')}`)
resolve(output.join(''))
});
process.on('err', (err) => {
console.log(`child process errored`, err);
});
process.stdin.on('error', err => {
console.log(`child process stdin emitted error, invalid filter?`);
})
process.stdin.write(stdin)
process.stdin.end()
})
}