-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
176 lines (136 loc) · 4.44 KB
/
app.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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
const fs = require('fs');
const _ = require('lodash');
const path = require('path');
const express = require('express');
const JWT = require('jsonwebtoken');
const config = require('./config');
const httpClient = require('./http-client');
const codeGen = require('./generator/index');
const logger = global.logger;
const token = JWT.sign({ name: 'DS_CM', _id: 'admin', isSuperAdmin: true }, config.RBAC_JWT_KEY);
global.CM_TOKEN = token;
if (!config.flowId) {
logger.error(`No Process Flow ID available. Shutting Down.`)
process.exit(1);
}
let url = config.baseUrlCM + '/' + config.app + '/processflow/' + config.flowId;
logger.info(`Requesting CM for Process Flow data :: ${url}`);
(async () => {
try {
let res = await httpClient.request({
url: url,
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'JWT ' + token
}
});
logger.info(`Reponse code :: ${res.statusCode}`);
if (res.statusCode !== 200) {
throw res.body;
}
const flowData = JSON.parse(JSON.stringify(res.body));
let nodeIds = _.map(flowData.nodes, e => e.nodeId);
let nodeUrl = `${config.baseUrlCM}/${config.app}/processnode?filter={ "_id": { "$in": ["${nodeIds.join('","')}"] } }`;
let nodeRes = await httpClient.request({
url: nodeUrl,
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'JWT ' + token
}
});
nodeIds.forEach(e => {
let node = _.find(nodeRes.body, n => n._id == e);
let index = _.findIndex(flowData.nodes, n => n.nodeId == e);
flowData.nodes[index].type = node.type;
flowData.nodes[index].name = node.name;
flowData.nodes[index].app = node.app;
flowData.nodes[index].api = node.api;
flowData.nodes[index].dataStructure = node.dataStructure;
});
config.appNamespace = flowData.namespace;
config.imageTag = flowData._id + ':' + flowData.version;
config.appDB = config.DATA_STACK_NAMESPACE + '-' + flowData.app;
config.port = flowData.port || config.port;
try {
await codeGen.createProject(flowData);
initialize();
} catch (err) {
logger.error(`Error Creating Files for Flow :: ${config.flowId} :: ${JSON.stringify(err)}`);
}
} catch (err) {
logger.error(`Error connecting to CM :: ${JSON.stringify(err)}`);
}
})();
async function initialize() {
try {
require('./db-factory.js');
global.promises = [];
const app = express();
const middlewares = require('./utils/lib.middlewares');
app.use(express.urlencoded({ extended: true }));
app.use(middlewares.addHeaders);
// app.get('/api/b2b/internal/export/route', async function (req, res) {
// let content = fs.readFileSync(path.join(__dirname, 'route.js'), 'utf-8');
// res.json({ content });
// });
app.use('/api/b2b/internal/health/ready', async function (req, res) {
try {
if (global.appcenterDB) {
return res.status(200).json({ message: 'Alive' });
}
return res.status(400).json({ message: 'DB Not Connected' });
} catch (err) {
logger.error(err);
return res.status(500).json({ message: err.message });
}
});
app.use('/api/flows', require('./router/route.js'));
const server = app.listen(config.port, function () {
logger.info(`Server Listening on port :: ${config.port}`);
});
let timeout = config.serverTimeout || 60;
if (typeof timeout == 'string') {
timeout = parseInt(timeout, 10);
}
server.setTimeout(timeout * 1000);
process.on('SIGTERM', () => {
try {
logger.info('+++++ Server Kill Request Recieved +++++');
// Handle Request for 15 sec then stop recieving
setTimeout(() => {
global.stopServer = true;
}, 15000);
const intVal = setInterval(() => {
// Waiting For all pending requests to finish;
if (global.activeRequest === 0) {
// Closing Express Server;
server.close(() => {
// Waiting For all DB Operations to finish;
Promise.all(global.dbPromises).then(() => {
logger.info('Server Stopped.');
process.exit(0);
}).catch(err => {
logger.error(err);
process.exit(0);
});
});
clearInterval(intVal);
} else {
logger.info(`Waiting for request to complete, Active Requests :: ${global.activeRequest}`);
}
}, 2000);
} catch (e) {
logger.error(`Error stopping server :: ${e}`);
throw e;
}
});
} catch (err) {
logger.error(`Error starting server :: ${err}`);
process.exit(0);
}
}