forked from apparatus/fuge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpServer.js
More file actions
144 lines (112 loc) · 3.86 KB
/
Copy pathhttpServer.js
File metadata and controls
144 lines (112 loc) · 3.86 KB
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
const express = require('express')
const Wreck = require("wreck");
function init(system, commands) {
function promisifyCommand(command = '', args = [], system) {
const commandObj = commands[command]
return new Promise((resolve, reject) => {
commandObj.action(args, system, (error, result) => {
if (error) {
reject(error)
}
resolve(result)
})
})
}
var app = express();
const port = getPortFromSystem(system)
const forwardPorts = getForwardPortsFromSystem(system)
console.log({ forwardPorts })
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
app.post('/api/commands/:command', consoleLogWrapper(async function (req, res) {
const command = req.params.command
const args = req.query.args || []
const result = await promisifyCommand(command, args, system).catch(err => 'error') || []
const forwardResults = await forwardRequest(forwardPorts, 'post', `/api/commands/${command}`, args )
res.send([ ...result, ...forwardResults]);
}));
app.use('/', express.static(__dirname + '/public'));
app.listen(port, function () {
console.log(`Fuge http server listening on port ${port}`);
console.log(`Open http client at http://localhost:${port}`);
});
}
function getPortFromSystem(system) {
const { global: { http_server } } = system
if (!http_server) {
return 3000
}
const port = http_server.find(it => it.match(/port=/)).replace(/port=/, '')
console.log('PORT', port)
return port
}
function getForwardPortsFromSystem(system) {
const { global: { http_server } } = system
if (!http_server) {
return []
}
const forwardToPorts = http_server.find(it => it.match(/forward_to_ports=/))
if (!forwardToPorts) {
return []
}
const ports = forwardToPorts.replace(/forward_to_ports=/, '').split(',')
console.log('PORTS', ports)
return ports
}
async function forwardRequest(forwardPorts, method, url, args) {
let results = []
const queryString = args.map(it => `args[]=${it}`).join('&')
for (let i = 0; i < forwardPorts.length; i++) {
url = `http://localhost:${forwardPorts[i]}${url}?${queryString}`
const body = await performRequest(method, url)
body.forEach(it => it.forwadPort = forwardPorts[i])
results = [...results, ...body]
}
return results
}
async function performRequest(method, url) {
const response = await await Wreck.request(method, url);
const bodyBuffer = await Wreck.read(response);
return parseBodyBuffer(bodyBuffer)
}
function parseBodyBuffer(bodyBuffer) {
bodyBuffer = bodyBuffer.toString()
try {
return JSON.parse(bodyBuffer)
} catch (error) {
return bodyBuffer
}
}
function consoleLogWrapper(cb) {
return async function (req, res) {
const originalLog = console.log
console.log = () => {}
const result = await cb(req, res)
console.log = originalLog
return result
}
}
module.exports = {
init
}
function parseTable(table) {
const splitted = table.split('\n')
const [ firstLine ] = splitted.splice(0, 1)
const columns = firstLine .replace(/\b\s\b/g, '-')
.match(/(\b[a-z-]+\s+\b)/g).map(it => ({
key: it.trim(),
length: it.length
}))
return splitted.map(nextLine => {
console.log('>', nextLine)
let substringStart = 0
return columns.reduce((previous, current) => {
const result = { ...previous, [current.key]: nextLine.substring(substringStart, substringStart + current.length).trim() }
substringStart += current.length
return result
}, {})
})
}