-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.js
155 lines (126 loc) · 4.58 KB
/
server.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
let {ROLE, CREDENTIALS_FILE, SWAGGER_SERVER, FGT_API_CREDENTIALS, bricksDomain} = process.env;
const fs = require('fs');
const path = require('path');
const currentPath = process.cwd();
if (!ROLE){
console.log("No ROLE Definition found. Assuming simple APIHUB")
process.exit(0);
}
console.log(`ENVIRONMENT VARIABLES: ROLE: ${ROLE}, ${FGT_API_CREDENTIALS ? `FGT API CREDENTIALS: ${FGT_API_CREDENTIALS}` : `CREDENTIALS_FILE: ${CREDENTIALS_FILE}`} and SWAGGER_SERVER: ${SWAGGER_SERVER}`)
function failServerBoot(reason){
console.error("Server boot failed: " + reason);
process.exit(1);
}
function runCommand(command, ...args){
const { spawn } = require("child_process");
const callback = args.pop()
const spawned = spawn(command, args, {shell: true, cwd: process.cwd(), env: {
...process.env,
NODE_ENV: process.env.NODE_ENV,
PATH: process.env.PATH
}});
const log = {
data: [],
error: []
}
function errorCallback(err, log, callback){
const error = new Error(`ERROR in child Process: ${err.message || err}\n
-- log: \n${log.data.join("\n")}\n
-- error: \n${log.error.join("\n")}`);
callback(error)
}
spawned.stdout.on("data", data => {
console.log(data.toString());
log.data.push(data.toString());
});
spawned.stderr.on("data", data => {
console.log(data.toString());
log.error.push(data.toString());
});
spawned.on('error', (error) => {
console.log(`error: ${error.message}`);
errorCallback(error, log, callback);
});
spawned.on("close", code => {
console.log(`child process exited with code ${code}`);
return code === 0 ? callback(undefined, log) : callback(new Error("exist code " + code), log);
});
return spawned;
}
function getWallet(){
switch (ROLE){
case "mah":
return "mah";
case "whs":
return 'wholesaler';
case "pha":
return "pharmacy";
default:
return ROLE;
}
}
function overWriteCredentialsByRole(){
fs.copyFileSync(path.join(currentPath, "..", "docker", "api", "env", CREDENTIALS_FILE),
path.join(currentPath, "config", `fgt-${getWallet()}-wallet`, "credentials.json"))
}
async function bootAPIServer(){
if (bricksDomain)
console.log("Booting FGT API server with bricksDomain: " + bricksDomain)
require(path.join(currentPath, "participants", ROLE, "index.js"));
}
async function bootSwagger(){
const YAML = require('yamljs');
const express = require('express');
const cors = require('cors');
const swaggerUi = require('swagger-ui-express');
const config = {
port: 3009,
server: SWAGGER_SERVER,
path: "./swagger/docs",
participant: ROLE.toUpperCase()
};
const PORT = config.port;
const PATH = config.path;
const PARTICIPANT = config.participant;
const API_SERVER = config.server;
console.log('[FGT-API] Swagger load config=', config);
const swaggerPathResolve = path.resolve(PATH, PARTICIPANT.toUpperCase() + '.yml');
const swaggerDocument = YAML.parse(fs.readFileSync(swaggerPathResolve, 'utf8'));
swaggerDocument.servers = [{url: API_SERVER}];
const options = {
customCss: '.swagger-ui .topbar { display: none }'
};
const app = express();
app.use(cors());
app.use(express.json());
app.use('/', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));
app.get('*', (req, res) => {
res.redirect('/');
});
app.listen(PORT, console.log(`[FGT-API] Swagger API DOC listening on :${PORT} and able to make requests to API: ${API_SERVER}`));
}
const setDashboard = async function(){
return new Promise((resolve, reject) => {
let cmd = ['npm', 'run', `build-api-${ROLE}-dashboard`]
runCommand(...cmd, (err, log1) => {
if (err)
return reject(err);
cmd = ['npm', 'run', `export-api-credentials`, "--", `--role=${ROLE}`, `--endPoint=${SWAGGER_SERVER}`];
runCommand(...cmd, (err, log2) => {
if (err)
return reject(err)
resolve(log2)
})
})
})
}
try {
overWriteCredentialsByRole();
setDashboard().then(_ => {
Promise.all([bootAPIServer(), bootSwagger()])
.then(_ => console.log(`Completed Boot`))
.catch(e => failServerBoot(e.message));
}).catch(e => failServerBoot(e.message))
} catch (e){
failServerBoot(e.message);
}