-
Notifications
You must be signed in to change notification settings - Fork 4
/
mongoGen.js
349 lines (329 loc) · 11.6 KB
/
mongoGen.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
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
#!/%PROGRAMFILES%/nodejs/node
console.log("Hello, mongoGen");
var app = require('app') ;
var mongo = require('mongodb');
var ObjectID = require('mongodb').ObjectID;
console.log(app.version);
require('./utilityFns');
require('./customer');
require('./product');
require('./productOptions');
require('./zaaGenerator');
app.toOutput = app.statsOut = function(line) {
console.log(line);
return line;
};
var Q = require('q');
var nsend = Q.nsend;
var db;
function run(){
var server = new mongo.Server('localhost', 27017, {auto_reconnect: true});
db = new mongo.Db('zza', server, {fsync:true}); //{safe: false});
app.reset();
return nsend(db,'open')
.then(insertData)
.fail(reportError)
.fin(function(){ db.close(); console.log('Closing database')})
.fin(displayStats);
}
run();
//*** Private functions
function insertData(){
// insert reference collections first
return Q.all([
insertCustomers(),
insertOrderStatuses(),
insertProducts(),
insertProductOptions(),
insertProductSizes()
])
.then(createCustomerOrders);
}
function insertCustomers() {
return getCleanCollection('Customer')
.then(function(collection){
var mCustomers = [];
var customers = app.customers;
customers.forEach(function(c){
mCustomers.push({
firstName: c.firstName,
lastName: c.lastName,
phone: c.phone,
email: c.email,
address: {
street: c.street,
city: c.city,
state: c.state,
zip: c.zip
}
});
});
return insertCollection(collection, mCustomers);
})
.then(getCustomers);
function getCustomers(collection){
return nsend(collection, "find")
.then(function(cursor){
return nsend(cursor, "toArray");
})
.then(function(items){
if (!items || items.length === 0) {
throw new Error("Expected some 'Customers'; didn't get them");
}
console.log("Got "+items.length+" 'Customers'");
app.reporter.stats[collection.collectionName] = items.length;
app.customers = items; // overwrite app-level customers!
return(collection);
});
}
}
function insertOrderStatuses() {
return getCleanCollection('OrderStatus')
.then(function(collection){
var mStatuses = [];
app.orderStatuses.forEach(function(s){
mStatuses.push({
_id: s.id,
name: s.name
});
});
return insertCollection(collection, mStatuses);
})
.then(verifyCollection);
}
function insertProducts() {
return getCleanCollection('Product')
.then(function(collection){
var mProducts = [];
var productTypes=['pizzas','salads','drinks'];
productTypes.forEach(function(typeName){
var products = app[typeName];
products.forEach(function(p){
mProducts.push({
_id: p.id,
type: p.type,
name: p.name,
description: p.description,
image: p.image,
hasOptions: p.hasOptions?true:false,
isPremium: p.isPremium?true:false,
isVegetarian: p.isVegetarian?true:false,
withTomatoSauce: p.withTomatoSauce?true:false,
sizeIds: p.sizeIds
});
});
});
return insertCollection(collection, mProducts);
})
.then(verifyCollection);
}
function insertProductOptions() {
return getCleanCollection('ProductOption')
.then(function(collection){
var mOptions = [];
var optionTypes=['crusts','sauces','cheeses','veggies','meats','spices','saladDressings'];
optionTypes.forEach(function(typeName){
var options = app[typeName];
options.forEach(function(o){
var productTypes = [];
if (o.isPizzaOption) {productTypes.push('pizza');}
if (o.isSaladOption) {productTypes.push('salad');}
mOptions.push({
_id: o.id,
type: o.type,
name: o.name,
factor: o.factor,
productTypes: productTypes
});
});
});
return insertCollection(collection, mOptions);
})
.then(verifyCollection);
}
function insertProductSizes() {
return getCleanCollection('ProductSize')
.then(function(collection){
var mSizes = [];
app.productSizes.forEach(function(s){
mSizes.push({
_id: s.id,
type: s.type,
name: s.name,
price: s.price,
premiumPrice: s.premiumPrice,
toppingPrice: s.toppingPrice,
isGlutenFree: s.isGlutenFree?true:false
});
});
return insertCollection(collection, mSizes);
})
.then(verifyCollection);
}
function createCustomerOrders(){
app.idGenerators.newOrderId = ObjectID; // use Mongo Id generator
var zzaGenerator = new app.ZzaGenerator();
var deferred = Q.defer();
var insertCounter = 0;
var incInsertCounter = function () {insertCounter +=1;};
var decInsertCounter = function (){
insertCounter -= 1;
if (insertCounter < 0){deferred.reject(new Error('insertCounter became negative'))}
if (insertCounter === 0){
console.log('Saved last order');
deferred.resolve(true);
}
};
console.log ('Creating and saving customer orders');
var ordersCollection;
getCleanCollection('Order')
.then(function(collection){
ordersCollection = collection;
app.reporter.report = report; // replace w/ mongo report fn
zzaGenerator.makeCustomerOrders(); // Optional integer param limits number of customers
});
return deferred.promise;
function report(customer){
app.reportCustomerOrderStats(customer);
var orders = customer.orders, ordsLen = orders.length;
for (var i = 0 ; i < ordsLen; i++){
var order = orders[i];
var mOrder = {
_id: order.id,
customerId: customer._id,
name: customer.firstName+' '+customer.lastName,
statusId: order.status.id,
status: order.status.name,
ordered: order.orderDate,
phone: order.phone,
delivered: order.deliveryDate,
deliveryCharge: order.deliveryCharge,
itemsTotal: order.itemsTotal
};
if (order.deliveryCharge){
mOrder.deliveryAddress = customer.address;
}
var mItems = [];
var items = order.items, itemsLen = items.length;
for (var j = 0; j < itemsLen; j++){
var item = items[j];
var mItem = {
productId: item.product.id,
name: item.product.name,
type: item.product.type,
sizeId: item.size.id,
size: item.size.name,
qty: item.qty,
unitPrice: item.unitPrice,
totalPrice: item.totalPrice
};
if (item.instructions) {
mItem.instructions = item.instructions;
}
var opts = item.options;
if (opts.length){
var mOpts = [];
opts.forEach(function(opt){
mOpts.push({
optionId: opt.option.id,
name: opt.option.name,
qty: opt.qty,
price: opt.price
});
});
mItem.options = mOpts;
}
mItems.push(mItem);
}
mOrder.items = mItems;
incInsertCounter();
ordersCollection.insert(mOrder, {safe: true}, function(err, recs){
if (err){
var msg = "Error on mOrder insert of id "+mOrder._id;
var fullMsg = msg + "\n:"+err.message;
console.log(fullMsg);
console.dir(mOrder);
err = new Error(msg + "; see console");
deferred.reject(err);
throw err; // hope to terminate further processing
} else {
decInsertCounter();
}
});
}
}
}
function displayStats(){
var statsOut = app.statsOut;
statsOut("\n=== STATS ===");
statsOut(JSON.stringify(app.reporter.stats, null, 2));
}
//*** Utility functions ***
function getCleanCollection(collectionName){
var getCollection = function(){return nsend(db, 'collection', collectionName);};
return getCollection()
.then(function(collection) {
// 'drop' is faster than 'remove' and kills indexes
return nsend(collection, "drop");
})
// whether 'drop' succeeds or fails, create the new collection
.then(getCollection, getCollection)
// Paranoia testing
.then(function(collection){
return nsend(collection, 'count')
.then(function(count){
if (count !=0) {
throw new Error("test collection not empty after remove call");
}
return collection;
});
})
}
function insertCollection(collection, data){
return nsend(collection, 'insert', data)
.then(function(){
return collection});
}
function verifyCollection(collection){
return nsend(collection, 'find')
.then(function(cursor){
return nsend(cursor, 'toArray');
})
.then(function(items){
var collectionName = collection.collectionName;
if (!items || items.length === 0) {
throw new Error("Expected some '" + collectionName + "' items; didn't get them");
}
var count = items.length;
console.log("Got "+count+" '"+collectionName+"' item(s)");
if (count>3){
console.log("First three from '"+collectionName+"':");
console.dir(items.slice(0,3),'items');
console.log("...");
} else {
console.dir(items,'items') ;
}
app.reporter.stats[collectionName] = count;
return collection;
});
}
function reportError(err){
console.log('!!! run error:');
console.dir(err);
}
//*** Test/Explore ***
// For exploratory purposes
// Call it within insertData()
/*
function insertTestItems(){
return getCleanCollection('test')
.then(function(collection){
return insertCollection(collection, [
{name:"The Dude"},
{name: "Walter"},
{name: "Donny"}
]);
})
.then(verifyCollection);
}
*/