-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdatabase.js
More file actions
587 lines (488 loc) · 18.2 KB
/
database.js
File metadata and controls
587 lines (488 loc) · 18.2 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
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//-----------------------------------------------------------------------------
// Name: dhDatabase Service
//
// Purpose: Microservice
//
// Interfaces: MongoDB database
//
// Author: Sal Carceller
//
//-----------------------------------------------------------------------------
var http = require('http');
var url = require('url');
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var mongoClient = require('mongodb').MongoClient;
var helper = require('./dhCommon/helpers'); // include helper functions from helpers.js
//-----------------------------------------------------------------------------
// Set up express
var app = express();
var server = http.createServer(app);
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json()); // for parsing application/json
//-----------------------------------------------------------------------------
// what host and port should we listen on?
//var _host = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'; // host to listen on
var _port = process.env.OPENSHIFT_NODEJS_PORT || 8080; // port to listen on
//-----------------------------------------------------------------------------
// return code definitions, used in json responses {"RC": _rcOK}
var _rcOK = 0;
var _rcWarning = 1;
var _rcError = 2;
var _rcUnknown = 99;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Main code body
//-----------------------------------------------------------------------------
//var mongourl = process.env.mongourl;
//var replaced = mongourl.replace(/%([^%]+)%/g, function(_,n)
//{
// return process.env[n];
//})
//mongourl = replaced;
console.log("DreamHome.dhDatabase service ==> Begin Execution.");
// wait for DB module to fully initialize and connect to the backend DB
// we don't want to start the node.js server listening till we know we are fully connected to the DB
helper.dbInit( function(err)
{
if(!err)
{ // DB connections have been established.
console.log(' ... application has successfully connected to the DB');
}
else
{ // OH no! something has gone wrong building DB connections!
// we still proceed and start the server listening
// but we mark the server as having a severe DB connection error!
console.log(' ... WARNING: application failed to connect with the backend DB!');
}
// Start the node.js server listening
// even if the backend DB connection fails we still want to service requests
app.listen(_port);
console.log(' ... application now listening on port ' + _port);
});
//-----------------------------------------------------------------------------
// Checks if we are connected to the DB and reports list of all collections
//-----------------------------------------------------------------------------
app.get('/dbConnected', function(req, res)
{
var retjson = {"RC":_rcOK}; // assume a good json response
var statusCode = 200; // assume valid http response code=200 (OK, good response)
// test if connected to the DB
if(helper.dbConnected()==true)
{ // connected to the DB
retjson.success = "Succesfully connected to the DB.";
// Let's fetch the list of collections currently stored in the DB
helper.dbref().listCollections().toArray(function(err, items)
{
// get the dbName
retjson.dbName = helper.dbName();
// add the list of collections found to the return JSON
retjson.collections = items;
// send the http response message
helper.httpJsonResponse(res,statusCode,retjson);
});
}
else
{ // not connected to the DB
retjson.RC = _rcError;
retjson.error = "ERROR: we are not connected to the DB!";
statusCode = 500; // internal error while connecting to the DB
// send the http response message
helper.httpJsonResponse(res,statusCode,retjson);
}
return;
});
//-----------------------------------------------------------------------------
// creates the database
//-----------------------------------------------------------------------------
app.get('/dbCreate', function (req, res)
{
var retjson = {"RC":_rcOK}; // assume a good json response
var statusCode = 200; // assume valid http response code=200 (OK, good response)
// test if connected to the DB
if(helper.dbConnected()==true)
{ // connected to the DB
// Create Counter Collection and be sure it's built prior to building any other collections.
_createCounterColl(
function(err)
{ // callback, called when Counter collection is fully built and initialized.
if(!err)
{ // Counter collection is now fully built
// we can safely proceed to build the other collections
console.log(' ... Counter collection created successfully.' );
// Now we will create the remaining collections, but WITHOUT any callbacks
// we will assume everything builds correctly and check on the status later.
// Create Client Collection
_createClientColl();
// Create Agent Collection
_createAgentColl();
// Create Office Collection
_createNotificationColl();
// Create Office Collection
_createOfficeColl();
// Create Property Collection
_createPropertyColl();
}
});
retjson.success = "DB create processed successfull but NOT verified!";
// send the http response message
helper.httpJsonResponse(res,statusCode,retjson);
}
else
{ // not connected to the DB
retjson = {};
retjson.RC = _rcError;
retjson.error = "ERROR: we are not connected to the DB!";
statusCode = 500; // internal error while connecting to the DB
// send the http response message
helper.httpJsonResponse(res,statusCode,retjson);
}
return;
});
//-----------------------------------------------------------------------------
// delete the database
//-----------------------------------------------------------------------------
app.get('/dbDelete', function (req, res)
{
var retjson = {"RC":_rcOK}; // assume a good json response
var statusCode = 200; // assume valid http response code=200 (OK, good response)
// test if connected to the DB
if(helper.dbConnected()==true)
{ // connected to the DB
// delete the database
_deleteDB();
retjson.success = "DB deleted successfully!";
}
else
{ // not connected to the DB
retjson = {};
retjson.RC = _rcError;
retjson.error = "ERROR: we are not connected to the DB!";
statusCode = 500; // internal error while connecting to the DB
}
// send the http response message
helper.httpJsonResponse(res,statusCode,retjson);
return;
});
//-----------------------------------------------------------------------------
// functions to get/fetch records from the collections
//-----------------------------------------------------------------------------
app.get('/clients', function (req, res)
{
// console.log("app.get(./clients function has been called.");
var cref = helper.crefClient();
var dbQuery = {}; // query used for looking up records in the collection
// fetch records from the collection based on the query desired.
cref.find(dbQuery).toArray( function(err, items)
{
if(!err)
{
// send the http response message
var retjson = {"RC":_rcOK}; // assume a good json response
var statusCode = 200; // assume valid http response code=200 (OK, good response)
retjson.items = items;
// send the http response message
helper.httpJsonResponse(res,statusCode,retjson);
}
});
return;
});
app.get('/agents', function (req, res)
{
// console.log("app.get(./agents function has been called.");
var cref = helper.crefAgent();
var dbQuery = {}; // query used for looking up records in the collection
// fetch records from the collection based on the query desired.
cref.find(dbQuery).toArray( function(err, items)
{
if(!err)
{
// send the http response message
var retjson = {"RC":_rcOK}; // assume a good json response
var statusCode = 200; // assume valid http response code=200 (OK, good response)
retjson.items = items;
// send the http response message
helper.httpJsonResponse(res,statusCode,retjson);
}
});
return;
});
// functions to get/fetch records from the collections
app.get('/offices', function (req, res)
{
// console.log("app.get(./offices function has been called.");
var cref = helper.crefOffice();
var dbQuery = {}; // query used for looking up records in the collection
// fetch records from the collection based on the query desired.
cref.find(dbQuery).toArray( function(err, items)
{
if(!err)
{
// send the http response message
var retjson = {"RC":_rcOK}; // assume a good json response
var statusCode = 200; // assume valid http response code=200 (OK, good response)
retjson.items = items;
// send the http response message
helper.httpJsonResponse(res,statusCode,retjson);
}
});
return;
});
app.get('/properties', function (req, res)
{
// console.log("app.get(./properties function has been called.");
var cref = helper.crefProperty();
var dbQuery = {}; // query used for looking up records in the collection
// fetch records from the collection based on the query desired.
cref.find(dbQuery).toArray( function(err, items)
{
if(!err)
{
// send the http response message
var retjson = {"RC":_rcOK}; // assume a good json response
var statusCode = 200; // assume valid http response code=200 (OK, good response)
retjson.items = items;
// send the http response message
helper.httpJsonResponse(res,statusCode,retjson);
}
});
return;
});
app.get('/notifications', function (req, res)
{
// console.log("app.get(./notifications function has been called.");
var cref = helper.crefNotification();
var dbQuery = {}; // query used for looking up records in the collection
// fetch records from the collection based on the query desired.
cref.find(dbQuery).toArray( function(err, items)
{
if(!err)
{
// send the http response message
var retjson = {"RC":_rcOK}; // assume a good json response
var statusCode = 200; // assume valid http response code=200 (OK, good response)
retjson.items = items;
// send the http response message
helper.httpJsonResponse(res,statusCode,retjson);
}
});
return;
});
//-----------------------------------------------------------------------------
// Simple echo get method, used to sanity test service
//-----------------------------------------------------------------------------
app.get('/echo', function (req, res)
{
// console.log("app.get(./echo function has been called.");
var retjson = {"RC":_rcOK}; // assume a good json response
var statusCode = 200; // assume valid http response code=200 (OK, good response)
// send the http response message
retjson.success = "Echo from DreamHome.dhDatabase service!";
res.status(statusCode).json(retjson);
res.end;
return;
});
//-----------------------------------------------------------------------------
// Private function start here
//-----------------------------------------------------------------------------
// create the Counter collection that's used for uniqueIDs
function _createCounterColl(callback)
{
helper.createCounterColl(callback);
return;
}
function _createClientColl()
{
// get refrence handle to the Client collection
var cref = helper.crefClient();
// create and add the first client record to the Client collection.
// generate a unique Client Id key for this real-estate client record
helper.genClientId(
function(err, pkId)
{
if(!err)
{ // pkId generated
var jsonRecord =
{clientId:pkId,
clientName:{clientFN:'Richard',clientLN:'Hendrix'},
clientInfo:{address:'101 Valley Steet',city:'Glendale',state:'California',zip:'91201',phone:'555-676-8907',email:'[email protected]'},
agentId:1000,
suggestedProperties:[{propertyId:2000,propertyState:0,askingPrice:320000.00,rating:0,comments:[{comment:'This is a beautiful home'}]}],
minAskingPrice:200000.00,
maxAskingPrice:400000.00
};
cref.insertOne( jsonRecord, {w:1, j:true},
function(err,result)
{
if(!err)
{
console.log("Client record "+pkId+" added to Client collection.");
}
});
}
});
return;
}
function _createAgentColl()
{
// get refrence handle to the Agent collection
var cref = helper.crefAgent();
// create and add the first agent record to the Agent collection.
// generate a unique Agent Id key for this real-estate agent record
helper.genAgentId(
function(err, pkId)
{
if(!err)
{ // pkId generated
var jsonRecord =
{agentId:pkId,
agentData:{agentFN:'Dinesh',agentLN:'Chugtai',agentLicense:'CAL-34917'},
officeId:3000,
properties:[{propertyId:'2000',clientId:'4000',propertyState:0}]
};
cref.insertOne( jsonRecord, {w:1, j:true},
function(err,result)
{
if(!err)
{
console.log("Agent record "+pkId+" added to Agent collection.");
}
});
}
});
return;
}
function _createNotificationColl()
{
// get refrence handle to the Notification collection
var cref = helper.crefNotification();
// create and add the first notify record to the Notification collection.
// generate a unique Notification Id key for this real-estate notification record
helper.genNotificationId(
function(err, pkId)
{
if(!err)
{ // pkId generated
var jsonRecord =
{notificationId:pkId,agentId:1000,clientId:4000};
cref.insertOne( jsonRecord, {w:1, j:true},
function(err,result)
{
if(!err)
{
console.log("Notification record "+pkId+" added to Notification collection.");
}
});
}
});
return;
}
function _createOfficeColl()
{
// get refrence handle to the Office collection
var cref = helper.crefOffice();
// create and add the first office record to the Office collection.
// generate a unique Office Id key for this real-estate Office record
helper.genOfficeId(
function(err, pkId)
{
if(!err)
{ // pkId generated
var jsonRecord =
{officeId:pkId,officeName:'Valley North',officeManager:'Erlich Bachman',
officeAddr:{address:'223 Mountain Drive',city:'Buena Vista',state:'California',zip:'91220'},
numProperties:0
};
cref.insertOne( jsonRecord, {w:1, j:true},
function(err,result)
{
if(!err)
{
console.log("Office record "+pkId+" added to Office collection.");
}
});
}
});
return;
}
// create the Property collection and add a few property records to the collection.
function _createPropertyColl()
{
// get refrence handle to the Property collection
var cref = helper.crefProperty();
// create and add the first property record to the Property collection.
// generate a unique Property Id key for this real-estate property record
helper.genPropertyId(
function(err, pkId)
{
if(!err)
{ // pkId generated
var jsonRecord =
{propertyId:pkId,
location:{address:'1024 College',city:'Wheaton',state:'California',zip:'91330',longitude:'35.601623',latitude:'-78.245908'},
sqFeet:2895,numBeds:4,numBaths:3,yearBuilt:'1970',description:'Two blocks from university',askingPrice:233000.00
};
cref.insertOne( jsonRecord, {w:1, j:true},
function(err,result)
{
if(!err)
{
console.log("Property record "+pkId+" added to Property collection.");
}
});
}
});
// create and another property record to the Property collection.
// generate a unique Property Id key for this real-estate property record
helper.genPropertyId(
function(err, pkId)
{
if(!err)
{ // pkId generated
var jsonRecord =
{propertyId:pkId,
location:{address:'435 Main',city:'Springfield',state:'California',zip:'91440',longitude:'36.507623',latitude:'-79.145509'},
sqFeet:3200,numBeds:5,numBaths:3,yearBuilt:'1982',description:'Nice cottage by lake',askingPrice:345000.00
};
cref.insertOne( jsonRecord, {w:1, j:true},
function(err,result)
{
if(!err)
{
console.log("Property record "+pkId+" added to Property collection.");
}
});
}
});
// create and another property record to the Property collection.
// generate a unique Property Id key for this real-estate property record
helper.genPropertyId(
function(err, pkId)
{
if(!err)
{ // pkId generated
var jsonRecord =
{propertyId:pkId,
location:{address:'2240',street:'Berlin',city:'Florence',state:'California',zip:'92340',longitude:'31.086579',latitude:'-72.357987'},
sqFeet:3950,numBeds:5,numBaths:5,yearBuilt:'1967',description:'Mansion in the city',askingPrice:312000.00
};
cref.insertOne( jsonRecord, {w:1, j:true},
function(err,result)
{
if(!err)
{
console.log("Property record "+pkId+" added to Property collection.");
}
});
}
});
return;
}
// deletes the database completely, does a drop DB
function _deleteDB()
{
// drop the entire database
helper.dbref().dropDatabase();
return;
}