forked from urfu-2015/webdev-tasks-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongoquery.js
97 lines (88 loc) · 2.61 KB
/
mongoquery.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
'use strict';
const MONGO_CLIENT = require('mongodb').MongoClient;
/**
* Îáüåêò, äåëàþùèé îäèí çàïðîñ ê ÁÄ
* @constructor
* @param {string} dbString - URL ÁÄ
* @param {string} collectionName - Íàçâàíèå êîëëåêöèè
* @param {object} params - Ïàðàìåòðû çàïðîñà
* @param {object} methodParams - Ïàðàìåòðû ìåòîäà
* @param {booleam} needToTransformToArray - Íåîáõîäèìî ëè ïðèâîäèòü çàïðîñ ê ìàññèâó
* @param {function} callback - Callback
*/
var MongoQuery = function (dbString, collectionName, method, params, methodParams, needToTransformToArray, callback) {
this.__dbString = dbString;
this.__collectionName = collectionName;
this.__method = method;
this.__params = params;
this.__methodParams = methodParams;
this.__needToTransformToArray = needToTransformToArray;
this.__callback = callback;
this.__db = null;
this.__collection = null;
};
/**
* Ñòàðò çàïðîñà
*/
MongoQuery.prototype.start = function () {
try {
MONGO_CLIENT.connect(this.__dbString,
this.__createCollectionObject.bind(this));
} catch (e) {
return this.__callback(e);
}
};
/**
* Çàêðûòü ïîäêëþ÷åíèå è âûçâàòü êîëëáýê ñ îøèáêîé
* @private
* @param {object} err - Îøèáêà
*/
MongoQuery.prototype.__closeOnErrorAndCallback = function (err) {
this.__db && this.__db.close();
this.__callback(err);
};
/**
* Ïîëó÷èòü êîëëåêöèþ
* @private
* @param {object} err - Îøèáêà
* @param {object} db - ÁÄ
*/
MongoQuery.prototype.__createCollectionObject = function (err, db) {
if (err) {
return this.__closeOnErrorAndCallback(err);
}
this.__db = db;
db.collection(this.__collectionName, this.__performOperation.bind(this));
};
/**
* Âûïîëíèòü çàïðîñ
* @private
* @param {object} err - Îøèáêà
* @param {object} collection - Êîëëåêöèÿ
*/
MongoQuery.prototype.__performOperation = function (err, collection) {
if (err) {
return this.__closeOnErrorAndCallback(err);
}
this.__collection = collection;
if (this.__needToTransformToArray) {
collection[this.__method](this.__params)
.toArray(this.__returnResults.bind(this));
} else if (this.__methodParams) {
collection[this.__method](this.__params, this.__methodParams,
this.__returnResults.bind(this));
} else {
collection[this.__method](this.__params, this.__returnResults.bind(this));
}
};
/**
* Âåðíóòü ðåçóëüòàòû
* @private
* @param {object} err - Îøèáêà
* @param {object} data - Äàííûå
*/
MongoQuery.prototype.__returnResults = function (err, data) {
this.__db.close();
return this.__callback(err, data);
};
module.exports = MongoQuery;