forked from SAP-samples/cap-sflight
-
Notifications
You must be signed in to change notification settings - Fork 2
/
karma-cap-middleware.js
77 lines (62 loc) · 2.02 KB
/
karma-cap-middleware.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
const spawn = require("cross-spawn"),
HttpProxy = require("http-proxy");
function spawnServer(cmd, args, cwd, fnIsReady) {
return new Promise((resolve, reject) => {
const proc = spawn(cmd, args, {
cwd,
env: Object.assign({ PORT: 0 }, process.env),
stdio: ["ignore", "pipe", "inherit"],
});
const checkServerReady = (data) => {
const targetUrl = fnIsReady(data.toString());
if (targetUrl) {
proc.stdout.removeListener("data", checkServerReady);
resolve(targetUrl);
}
};
proc.on("close", reject);
proc.stdout.on("data", checkServerReady);
// clean up sub process
process.on("exit", () => {
if (proc) proc.kill();
});
});
}
function createKarmaMiddleware(serverUrl, auth) {
const proxyOptions = {
target: serverUrl,
auth: auth ? `${auth.user}:${auth.password}` : undefined,
};
const middleware = (logFactory) => {
const log = logFactory.create("cap-server");
const proxy = new HttpProxy(proxyOptions);
proxy.on("error", (data) => log.error(data.toString()));
return (req, res) => proxy.web(req, res);
};
middleware.$inject = ["logger"];
return { "middleware:cap-proxy": ["factory", middleware] };
}
async function java() {
const isReady = (data) => {
const started = data.match(/started on port\(s\): (?<port>\d+)/);
if (started) return new URL(`http://localhost:${started.groups.port}`);
};
const serverUrl = await spawnServer(
"mvn",
["spring-boot:run", "-B", "-Dserver.port=0"],
"../../srv",
isReady
);
return createKarmaMiddleware(serverUrl, { user: "admin", password: "admin" });
}
async function node() {
const isReady = (data) => {
const started = data.match(/server listening on {.*url:.*'(?<url>.+)'.*}/);
if (started) {
return new URL(started.groups.url);
}
};
const serverUrl = await spawnServer("npm", ["start"], "../..", isReady);
return createKarmaMiddleware(serverUrl, { user: "admin", password: "admin" });
}
module.exports = { java, node };