summaryrefslogtreecommitdiff
path: root/app/node_modules/okdb/index.js
blob: ad8d9a7e5f1679773b0380ade786c40b5baf771d (plain)
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
var assign = require('object-assign')
var cloneDeep = require('lodash.clonedeep');
var isobject = require('lodash.isobject');
var format = require('util').format;
var low = require('lowdb');
var Q = require('q');

low.mixin(low.mixin(require('underscore-db')));

/**
 * OKDB!
 * Minimal interface over a database of named collections of documents.
 */
function OKDB(options) {
  if (!(this instanceof OKDB)) return new OKDB(options);
  options = options || {};
  var db;
  if (typeof options === 'string')
    db = options;
  else
    db = options.db;
  if (!db)
    throw new Error('No DB db provided to OKDB');
  switch (db) {
    case 'fs':
      return FSDB(options);
    default:
      throw new Error('Invalid DB type');
  }
}

/**
 * DB implementation backed by a JSON file.
 */
function FSDB(options) {
  if (!(this instanceof FSDB)) return new FSDB(options);
  options = options || {};
  if (!options.schemas)
    throw new Error('No schemas provided to FSDB')
  this._schemas = options.schemas;
  var name = options.name || 'db';
  var filename = name + '.json';
  this._db = low(filename);
}

FSDB.prototype.get = function(collection, id) {
  var schema = this._schemas[collection];
  if (!schema)
    return resolve(null, new Error('No such collection type'));

  var query = getQuery(schema, id);
  if (!query)
    return resolve(null, new Error('Bad query'));

  var result = this._db(collection).find(query);
  return resolve(result ? cloneDeep(result) : result);
};

/**
 * Add a new document to the DB
 */
FSDB.prototype.insert = function(collection, data) {
  var schema = this._schemas[collection];
  var wrapped = this._db(collection);
  if (!schema)
    return resolve(null, new Error('No such collection type'));
  // Get detached, clone deep, data sleep, beep beep
  data = cloneDeep(data);
  // Auto-increment fields
  data = autoincrement(wrapped, schema, data);
  // Record date created
  // TODO Should this meta prop logic be moved out of the DB?
  data.dateCreated = new Date().toUTCString();
  var result = wrapped.chain().push(data).last().value();

  if (result) {
    return resolve(cloneDeep(result));
  } else {
    return resolve(null, new Error('Problem inserting document'));
  }
};

/**
 * Update an existing document in the DB
 */
FSDB.prototype.update = function(collection, id, data) {
  var schema = this._schemas[collection];
  if (!schema)
    return resolve(null, new Error('No such collection type'));

  var query = getQuery(schema, id);
  var wrapped = this._db(collection);
  var chain = wrapped.chain().find(query);

  if (!chain.value()) {
    return resolve(null, new Error('Cannot update nonexistent entry'));
  }

  var result = chain.assign(cloneDeep(data)).value();
  if (result) {
    return resolve(cloneDeep(result));
  } else {
    return resolve(null, new Error('Problem updating document'));
  }
};

/**
 * TODO Should be atomic ¯\_(ツ)_/¯
 */
FSDB.prototype.updateBatch = function(collection, ids, datas) {
  var schema = this._schemas[collection];
  if (!schema)
    return resolve(null, new Error('No such collection type'));
  if (!ids || !ids.length || !datas || !datas.length ||
      ids.length !== datas.length) {
    return resolve(null, new Error('Bad input'));
  }

  var doc = this._db(collection);
  var results = ids.map(function(id, i) {
    return doc.chain().find(getQuery(schema, id)).assign(datas[i]).value();
  });

  return resolve(results);
};

FSDB.prototype.remove = function(collection, id) {
  var schema = this._schemas[collection];
  if (!schema)
    return resolve(null, new Error('No such collection type'));

  var query = getQuery(schema, id);
  var result = this._db(collection).removeWhere(query);

  if (result) {
    // Don't need to clone this ref, since it's removed anyway
    return resolve(result);
  } else {
    return resolve(null, new Error('Cannot remove nonexistent entry'));
  }
};

FSDB.prototype.sortBy = function(collection, prop, descend) {
  var schema = this._schemas[collection];
  if (!schema)
    return resolve(null, new Error('No such collection type'));
  if (!prop)
    return resolve(null, new Error('Bad input'));

  var result = this._db(collection).sortByOrder([prop], [!descend]);
  return resolve(result);
};

FSDB.prototype.find = function(collection, query) {
  var schema = this._schemas[collection];
  if (!schema)
    return resolve(null, new Error('No such collection type'));
  if (!query)
    return resolve(null, new Error('Bad input'));

  var result = this._db(collection).find(query);

  return resolve(cloneDeep(result));
};

FSDB.prototype.all = function(collection) {
  var schema = this._schemas[collection];
  if (!schema)
    return resolve(null, new Error('No such collection type'));

  var data = this._db(collection).value();
  return resolve(cloneDeep(data || []));
};

FSDB.prototype.getMeta = function() {
  var data = this._db('meta').first();
  return resolve(data || {});
};

/**
 * Function implementing DB auto increment support
 * Naive implementation, assumes DB is relatively small.
 */
function autoincrement(wrapper, schema, data) {
  return schema.autoIncrementFields.reduce(function(data, field) {
    var last = wrapper.chain().sortByOrder([field], [true]).last().value();
    var index = last ? last[field] : -1;
    var incremented = {};
    incremented[field] = (parseInt(index) + 1);
    return assign(data, incremented);
  }, data);
}

function getQuery(schema, id) {
  if (schema && id) {
    var query = {};
    query[schema.idField] = id;
    return query;
  }
}

/**
 * Helper function to create promises for DB data
 */
function resolve(data, error) {
  return Q.promise(function resolvePromise(resolve, reject) {
    if (error) {
      reject(error);
    } else {
      resolve(data);
    }
  });
};


module.exports = OKDB;