UNPKG

1.96 kBJavaScriptView Raw
1var db_helper = require('./connection'),
2 logger = require('./logger');
3
4
5var Queriable = function () {
6
7 this.onDocLoad = function (fn) {
8 this.onDocLoadFn = fn;
9 };
10
11 this.find = function (id, cb) {
12 var db = db_helper.connection(),
13 self = this;
14
15 logger.info("Finding model for id %s", id);
16
17 db.get(id, function (err, doc) {
18 if (err) {
19 logger.error("Cannot find item with id %s error: %s", id, err);
20 cb(err, null);
21 return;
22 }
23 if(doc) {
24 try {
25 cb(null,self.onDocLoadFn(doc));
26 } catch(ex) {
27 dumpError(ex);
28 cb(ex,null);
29 }
30 } else {
31 cb("item does not exist", null);
32 }
33 });
34
35 };
36
37 this._view = function (view_name, view_options, cb) {
38 var _cb,
39 options,
40 db = db_helper.connection(),
41 self = this;
42
43 if (cb) {
44 _cb = cb;
45 options = view_options;
46 } else {
47 _cb = arguments[arguments.length - 1]
48 }
49
50
51 db.view(view_name, options, function (err, docs) {
52 if (err) {
53 return _cb(err, null);
54 }
55
56 var model_collection = [];
57
58 docs.forEach(function (doc) {
59 model_collection.push(self.onDocLoadFn(doc));
60 });
61
62 _cb(null, model_collection);
63 });
64
65
66 };
67
68
69 this.all = function (cb) {
70
71 this._view(this.model_type + '/all',cb);
72
73 };
74
75 this.where = function (property, key,cb) {
76
77 this._view(this.model_type + '/'+property,{key: key}, cb);
78 };
79
80
81
82};
83
84module.exports = Queriable;
85
86
87function dumpError(err) {
88 if (typeof err === 'object') {
89 if (err.message) {
90 logger.error('\nMessage: ' + err.message)
91 }
92 if (err.stack) {
93 logger.error('\nStacktrace:')
94 logger.error('====================')
95 logger.error(err.stack);
96 }
97
98 if (err.error) {
99 //console.dir(err);
100 }
101 } else {
102 logger.error('dumpError :: argument is not an object');
103 }
104}
105