-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
341 lines (300 loc) · 12.3 KB
/
db.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
/* Dotenv file used to access constants */
const dotenv = require('dotenv');
/* Mongoose is used for database functions */
const mongoose = require('mongoose');
/* Additional middleware for storing and displaying images */
const path = require('path');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const multer = require('multer');
const gridFsStorage = require('multer-gridfs-storage');
const grid = require('gridfs-stream');
/* Modify options to remove deprecation warnings */
const options = {
useNewUrlParser: true,
useUnifiedTopology: true
};
/* Configure dotenv with the needed data */
dotenv.config();
const url = process.env.DB_URL;
const urlTest = process.env.DB_URL_TEST;
/* Specify database operations (i.e., connecting to the database, creating the GridFS storage, and the database
* CRUD operations)
*/
const database = {
/**
* Connects to the database
*/
connect: function() {
if (process.env.NODE_ENV === 'test') {
const Mockgoose = require('mockgoose').Mockgoose;
const mockgoose = new Mockgoose(mongoose);
mockgoose.prepareStorage()
.then(function() {
mongoose.connect(urlTest, options, function(error) {
if (error) throw error;
console.log('Connected to: ' + url);
});
var connection = mongoose.createConnection(urlTest);
/* Initialize gfs */
var gfs;
connection.once('open', function() {
/* Initialize stream */
gfs = grid(connection.db, mongoose.mongo);
gfs.collection('uploads');
})
/* Create storage engine */
const storage = new gridFsStorage({
url: urlTest,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
const fileFilter = function(req, file, callback) {
/* Exclude the period preceding the file extension, and convert to lowercase */
const ext = path.extname(file.originalname).substr(1).toLowerCase();
let validExtension = false;
console.log(ext);
switch(ext) {
/* Fall through in all cases is deliberate */
case 'jpg':
case 'jpeg':
case 'jpe':
case 'jfif':
case 'heic':
case 'png':
case 'gif':
case 'webp':
case 'bmp':
case 'svg':
validExtension = true;
break;
default:
break;
}
if (!validExtension) {
return callback(new Error('This file type is not supported. Please upload a valid image.'))
}
callback(null, true)
}
const upload = multer({ storage, fileFilter });
return upload;
})
} else {
mongoose.connect(url, options, function(error) {
if (error) throw error;
console.log('Connected to: ' + url);
});
var connection = mongoose.createConnection(url);
/* Initialize gfs */
var gfs;
connection.once('open', function() {
/* Initialize stream */
gfs = grid(connection.db, mongoose.mongo);
gfs.collection('uploads');
})
/* Create storage engine */
const storage = new gridFsStorage({
url: url,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
const fileFilter = function(req, file, callback) {
/* Exclude the period preceding the file extension, and convert to lowercase */
const ext = path.extname(file.originalname).substr(1).toLowerCase();
let validExtension = false;
console.log(ext);
switch(ext) {
/* Fall through in all cases is deliberate */
case 'jpg':
case 'jpeg':
case 'jpe':
case 'jfif':
case 'heic':
case 'png':
case 'gif':
case 'webp':
case 'bmp':
case 'svg':
validExtension = true;
break;
default:
break;
}
if (!validExtension) {
return callback(new Error('This file type is not supported. Please upload a valid image.'))
}
callback(null, true)
}
const upload = multer({ storage, fileFilter });
return upload;
}
},
/**
* Inserts one document into the database
*
* @param model collection to be accessed
* @param doc document to be inserted
* @param callback callback for indicating whether the insertion succeeded
* @return whether the insertion succeeded
*/
insertOne: function(model, doc, callback) {
model.create (doc, function(error, result) {
if (error) return callback(false);
console.log('Added ' + result);
return callback(result);
});
},
/**
* Inserts multiple documents into the database
*
* @param model collection to be accessed
* @param docs documents to be inserted
* @param callback callback for indicating whether the insertion succeeded
* @return whether the insertion succeeded
*/
insertMany: function (model, docs, callback) {
model.insertMany (docs, function(error, result) {
if(error) return callback(false);
console.log('Added ' + result);
return callback(true);
});
},
/**
* Retrieves one document from the database
*
* @param model collection to be accessed
* @param query query to be executed on the collection
* @param projection fields to be returned
* @param callback callback for indicating whether the search succeeded
* @return false if the searching did not succeed; otherwise, the specified fields to be returned
*/
findOne: function(model, query, projection, callback) {
model.findOne (query, projection, function(error, result) {
if (error) return callback(false);
return callback(result);
});
},
/**
* Retrieves multiple documents from the database
*
* @param model collection to be accessed
* @param query query to be executed on the collection
* @param projection fields to be returned
* @param callback callback for indicating whether the search succeeded
* @return false if the searching did not succeed; otherwise, the specified fields to be returned
*/
findMany: function(model, query, projection, callback) {
model.find (query, projection, function(error, result) {
if (error) return callback(false);
return callback(result);
});
},
/**
* Updates one document in the database
*
* @param model collection to be accessed
* @param filter query with which to filter the collection documents
* @param update revisions to the document data
* @param callback callback for indicating whether the update succeeded
* @return whether the update succeeded
*/
updateOne: function(model, filter, update, callback) {
model.updateOne (filter, update, function(error, result) {
if (error) return callback(false);
console.log('Document modified: ' + result.nModified);
return callback(true);
});
},
/**
* Updates multiple documents in the database
*
* @param model collection to be accessed
* @param filter query with which to filter the collection documents
* @param update revisions to the document data
* @param callback callback for indicating whether the update succeeded
* @return whether the update succeeded
*/
updateMany: function(model, filter, update, callback) {
model.updateMany (filter, update, function(error, result) {
if (error) return callback(false);
console.log('Documents modified: ' + result.nModified);
return callback(true);
});
},
/**
* Deletes one document in the database
*
* @param model collection to be accessed
* @param conditions query with which to obtain the document to be deleted
* @param callback callback for indicating whether the deletion succeeded
* @return whether the deletion succeeded
*/
deleteOne: function(model, conditions, callback) {
model.deleteOne (conditions, function (error, result) {
if(error) return callback(false);
console.log('Document deleted: ' + result.deletedCount);
return callback(true);
});
},
/**
* Deletes multiple documents in the database
*
* @param model collection to be accessed
* @param conditions query with which to obtain the documents to be deleted
* @param callback callback for indicating whether the deletion succeeded
* @return whether the deletion succeeded
*/
deleteMany: function(model, conditions, callback) {
model.deleteMany (conditions, function (error, result) {
if(error) return callback(false);
console.log('Document deleted: ' + result.deletedCount);
return callback(true);
});
},
/**
* Converts a string to the ObjectId data type
*
* @param id string to be converted
* @return ObjectId variable of the input string
*/
convertToObjectId: function(id) {
return mongoose.Types.ObjectId(id);
},
updateOneIterative: function(model, filter, update) {
model.updateOne (filter, update, function(error, result) {
if (error) {
console.log('Error');
} else {
console.log('Document modified: ' + result.nModified);
console.log(result);
}
});
},
}
module.exports = database;