forked from tapd8/apig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datasource.js
278 lines (247 loc) · 7.22 KB
/
datasource.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/**
* @author lg<[email protected]>
* @date 5/17/19
* @description
*/
const log = require('./dist').log.app;
const request = require('request');
const path = require('path');
// const appConfig = require('./config');
const { getToken, removeToken } = require('./tapdata');
const checkEnableLoadSchemaFeature = require('./tapdata').checkEnableLoadSchemaFeature;
const MongoClient = require('mongodb').MongoClient;
const parse = require('mongodb-core').parseConnectionString;
const Conf = require('conf');
const config = new Conf();
const { getCollectionSchema } = require('./load_schema_mongo');
const getConnection = function (token) {
let url = config.get('tapDataServer.url') + '/api/Connections?access_token=' + token;
try {
let params = {
'filter[where][status]': 'testing',
'filter[where][database_type]': 'mongodb'
};
request.get(url, { qs: params, json: true }, function (err, response, body) {
if (err) {
log.error('get connection fail.', err);
} else if (response.statusCode === 200) {
if (body && body.length > 0) {
body.forEach(v => {
testConnection(v);
})
}
} else {
log.error('get connection error: \n', body);
}
});
} catch (e) {
log.error('get connection to test fail:\n', e);
}
},
testConnection = function (connection) {
try {
if (connection) {
//const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true";
const validOptionNames = [
'ssl',
'sslValidate',
'sslCA',
'sslCert',
'sslKey',
'sslPass',
'sslCRL',
'checkServerIdentity'
];
const validOptions = {
useNewUrlParser: true
};
let lbOptions = Object.keys(connection);
lbOptions.forEach(function(option) {
if (validOptionNames.indexOf(option) > -1) {
if( connection[option]){
validOptions[option] = connection[option];
}
}
});
if( validOptions.sslValidate) {
validOptions.sslCA = Array.isArray(validOptions.sslCA) ? validOptions.sslCA :
( validOptions.sslCA ? [validOptions.sslCA] : [])
} else {
delete validOptions.sslCA;
}
const uri = connection.database_uri;
const validate_details = [];
parse(uri, (err, uriObj) => {
validate_details.push({
"stage_code": "validate-3000",
"show_msg": "Checking the connection uri is available.",
"status": err ? "invalid" : "passed",
"sort": 1,
"error_code": null,
"fail_message": err ? err.toString() : null,
"required": true
});
if (err) {
log.error('connect to mongodb error\n', err);
updateConnection(connection.id, {
status: 'invalid',
response_body: {
validate_details: validate_details
}
}, function (err, data) { });
}
validate_details.push({
"stage_code": "validate-3100",
"show_msg": "Checking the connection database name is available.",
"status": uriObj['defaultDatabase'] ? "passed" : "invalid",
"sort": 1,
"error_code": null,
"fail_message": uriObj['defaultDatabase'] ? null : "No database name",
"required": true
});
if (!uriObj['defaultDatabase']) {
updateConnection(connection.id, {
status: 'invalid',
response_body: {
validate_details: validate_details
}
}, function (err, data) { });
} else {
const client = new MongoClient(uri, validOptions);
client.connect(err => {
validate_details.push({
"stage_code": "validate-3100",
"show_msg": "Checking the connection is available.",
"status": err ? "invalid" : "passed",
"sort": 1,
"error_code": null,
"fail_message": err ? err.toString() : null,
"required": true
});
if (err) {
log.error('connect to mongodb error\n', err);
updateConnection(connection.id, {
status: 'invalid',
response_body: {
validate_details: validate_details
}
}, function (err, data) {
client.close();
});
} else {
let databaseName = uriObj['defaultDatabase'] || 'test';
log.info('connect mongodb, database name is ' + databaseName);
databaseName = databaseName.split('/').join('_');
const db = client.db(databaseName);
db.collections(function (err, collections) {
let pending = 0;
const schema = {
tables: []
},
errors = [],
finish = function () {
pending--;
if (pending === 0) {
validate_details.push({
"stage_code": "validate-3200",
"show_msg": "Trying to load schema.",
"status": errors.length === 0 ? "passed" : "invalid",
"sort": 2,
"error_code": null,
"fail_message": errors.length > 0 ? errors.join("\n") : null,
"required": true
});
updateConnection(connection.id, {
status: 'ready',
schema: schema,
response_body: {
validate_details: validate_details
}
}, function (err, result) {
if (err) {
log.error('test mongodb connection fail\n', err);
} else {
log.info('test mongodb connection done.');
}
client.close();
});
}
};
collections.forEach((collection) => {
pending++;
getCollectionSchema(collection, function (err, collectionSchema) {
if (err) {
log.error('get collection schema fail\n', err);
errors.push(err);
} else {
schema.tables.push(collectionSchema);
}
finish();
});
});
});
}
});
}
});
}
} catch (e) {
log.error('test connection fail\n', e);
}
},
updateConnection = function (id, data, cb) {
log.info('update connection: ' + id);
getToken(function (token) {
let url = config.get('tapDataServer.url') + `/api/Connections/${id}?access_token=` + token;
try {
request({
url: url,
method: 'PATCH',
json: true,
body: data
}, function (err, response, body) {
if (err) {
log.error('update connection fail.', err);
cb(err, null);
} else if (response.statusCode === 401 || response.statusCode === 403) {
log.error('Access token Expired');
removeToken();
cb({
statusCode: response.statusCode,
msg: 'Access token expired'
}, null)
} else if (response.statusCode === 200) {
log.info('update connection success ' + id);
cb(null, body);
} else {
log.error('update connection error: \n', body);
cb(body, null);
}
});
} catch (e) {
log.error('update connection to test fail:\n', e);
cb(e, null);
}
});
};
let __intervalId = null;
exports.start = function () {
checkEnableLoadSchemaFeature(enable => {
if (enable) {
setInterval(() => {
try {
getToken(token => {
if (token)
getConnection(token);
})
} catch (e) {
log.error('get connection to test fail:\n', e);
}
}, 2000);
}
});
};
exports.stop = function () {
if (__intervalId)
clearInterval(__intervalId);
};