summaryrefslogtreecommitdiff
path: root/app/node_modules/okresource/index.js
blob: c1f2509e5e62b251a10508c821f5480ee9af2d6f (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
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
var format = require('util').format
var assign = require('object-assign');
var cloneDeep = require('lodash.clonedeep');
var Q = require('q');

/**
 * OKResource!
 * TODO Would be nicer to compose this with an existing resource
 * module, but haven't found a good fit. Should keep an eye on
 * 'resource' by bigcompany for an update.
 */
function OKResource(options) {
  if (!(this instanceof OKResource)) return new OKResource(options);
  options = options || {};
  if (!options.type)
    throw new Error('No resource type provided to OKResource')
  if (!options.schema)
    throw new Error('No schema provided to OKResource');
  if (!options.db)
    throw new Error('No DB provided to OKResource');

  var schema = options.schema;
  var spec = schema.spec;

  var type = options.type;
  var hasForeignKey = false
  this._db = options.db;
  this._schema = schema;

  var foreignKeys = Object.keys(spec).reduce(function(acc, field) {
    var fieldSpec = spec[field]
    if (fieldSpec.type === 'foreign-key') {
      hasForeignKey = true
      acc[field] = fieldSpec.key
    }
    return acc
  }, {})

  // Will store references to other resources referenced via foreign keys
  this._foreignKeyedResources = {}

  // Define properties which are part of the API
  
  // Should be treated as read-only
  Object.defineProperty(this, 'foreignKeys', {
    get: function() {
      return foreignKeys
    }
  })

  Object.defineProperty(this, 'hasForeignKey', {
    get: function() {
      return hasForeignKey
    }
  })

  Object.defineProperty(this, 'spec', {
    get: function() {
      return schema.spec;
    },
    enumerable: true
  });

  Object.defineProperty(this, 'type', {
    value: type,
    writable: false,
    enumerable: true
  });

  // Whether this resource represents a specific data point
  // or a whole class of data
  Object.defineProperty(this, 'bound', {
    value: false,
    writable: false,
    enumerable: true
  });
}

OKResource.prototype._linkForeignKey = function(field, resource) {
  this._foreignKeyedResources[field] = resource
}

/**
 * Fetch all related resources for the given field
 */
OKResource.prototype.related = function(field) {
  var resource = this._foreignKeyedResources[field]
  return Q.promise(function(resolve, reject) {
    if (!resource) {
      return error(reject, new Error(format(
          "No related resource for field '%s'", field)))
    }
    resource.all().then(resolve).fail(reject)
  })

  function error(reject, err) {
    setTimeout(function() {
      reject(err)
    }, 0)
  }
}

/**
 * Throws an error if data does not conform to schema
 */
OKResource.prototype.assertValid = function(data) {
  this._schema.assertValid(data);
};

OKResource.prototype.all = function() {
  return this._db.all(this.type);
};

OKResource.prototype.getID = function(data) {
  data = data || {};
  return data[this._schema.idField];
};

OKResource.prototype.create = function(data) {
  var type = this.type;
  var db = this._db;
  return Q.promise(function(resolve, reject) {
    if (!data) {
      reject(new Error('No data provided'));
    } else {
      db.insert(type, data).then(resolve).fail(reject);
    }
  });
};

OKResource.prototype.destroy = function(id) {
  var db = this._db;
  var type = this.type;
  return Q.promise(function(resolve, reject) {
    if (!id) {
      reject(new Error('No ID provided'));
    } else {
      db.remove(type, id).then(resolve).fail(reject);
    }
  });
};

OKResource.prototype.find = function(query) {
  query = query || {};
  var db = this._db;
  var type = this.type;
  return Q.promise(function(resolve, reject) {
    if (!query) {
      throw new Error('No query provided');
    } else {
      db.find(type, query).then(resolve).fail(reject);
    }
  });
};

OKResource.prototype.get = function(id) {
  var db = this._db;
  var type = this.type;
  return Q.promise(function(resolve, reject) {
    if (!id) {
      throw new Error('No ID provided');
    } else {
      db.get(type, id).then(resolve).fail(reject);
    }
  });
};

OKResource.prototype.update = function(id, data) {
  var db = this._db;
  var type = this.type;
  return Q.promise(function(resolve, reject) {
    if (!id) {
      reject(new Error('No resource ID provided'));
    } else if (!data) {
      reject(new Error('No data provided'));
    } else {
      db.update(type, id, data).then(resolve).fail(reject);;
    }
  });
};

OKResource.prototype.updateBatch = function(ids, datas) {
  var self = this;
  var db = this._db;
  var type = this.type;
  return Q.promise(function(resolve, reject) {
    if (!ids || !ids.length || !datas || !datas.length ||
        ids.length !== datas.length) {
      reject(new Error('Bad input'));
    } else {
      db.updateBatch(type, ids, datas).then(resolve).fail(reject);
    }
  });
}


/**
 * Get all documents in collection sorted by property,
 * optionally in descending order
 */
OKResource.prototype.sortBy = function(prop, descend) {
  return this._db.sortBy(this.type, prop, descend);
};

OKResource.prototype.updateOrCreate = function(id, data) {
  data = data || {};
  var type = this.type;
  var db = this._db;
  return Q.promise(function(resolve, reject) {
    if (!id) {
      reject(new Error('No ID provided'));
    } else {
      db.get(type, id).then(function(persisted) {
        if (persisted) {
          db.update(type, id, data).then(resolve).fail(reject);
        } else {
          db.insert(type, data).then(resolve).fail(reject);
        }
      }).fail(reject);
    }
  });
};

/**
 * Create special resource which is bound to particular data point
 * and has custom validation and query properties.
 */
OKResource.prototype.instance = function(options) {
  return new OKResourceInstance(this, {
    static: options.static
  });
};

/**
 * TODO This class is such bullshit. Refactor out
 */
function OKResourceInstance(resource, options) {
  if (!(this instanceof OKResourceInstance)) return new OKResourceInstance(options);
  // Only support static data instances for now
  if (!options.static)
    throw new Error(
      'Cannot create OKResourceInstance without static data');

  // Resources with static data are a special case. They exist
  // conceptually at all times since they are derived from app
  // configuration, but may not actually be present
  // in the database and need custom logic to handle this.
  var staticData = cloneDeep(options.static);
  var id = resource.getID(staticData);
  if (!id)
    throw new Error(
        'Cannot create static OKResourceInstance without an ID field');

  this.getID = function() {
    return id;
  };

  /**
   * Ensure that static data is provided on get
   */
  this.get = function() {
    return Q.promise(function(resolve, reject) {
      resource.get(id).then(function(data) {
        // Note the assign call. Don't expose private references!
        if (data) {
          resolve(assign(data, cloneDeep(staticData)));
        } else {
          resolve(cloneDeep(staticData));
        }
      }).fail(reject);
    });
  };

  this.update = function(id, data) {
    return Q.promise(function(resolve, reject) {
      var valid = Object.keys(staticData).every(function(prop) {
        return staticData[prop] === data[prop];
      });
      if (!valid) {
        reject(new Error('Cannot update resource\'s static data'));
      } else {
        // When updating static resources, we create them if
        // they don't actually exist in the DB
        resource.updateOrCreate(id, data).then(resolve).fail(reject);
      }
    });
  };

  this.updateOrCreate = function(id, data) {
    return Q.promise(function(resolve, reject) {
      reject(new Error('Cannot updateOrCreate static resource'));
    });
  };

  this.destroy = function(id) {
    return Q.promise(function(resolve, reject) {
      reject(new Error('Cannot destroy static resource'));
    });
  };

  this.all = function(id) {
    return Q.promise(function(resolve, reject) {
      reject(new Error('Cannot get all for static resource'));
    });
  };

  this.create = function(id) {
    return Q.promise(function(resolve, reject) {
      reject(new Error('Cannot create static resource'));
    });
  };

  this.find = function(id) {
    return Q.promise(function(resolve, reject) {
      reject(new Error('Cannot perform find on static resource'));
    });
  };

  this.assertValid = function(data) {
    data = data || {};
    Object.keys(staticData).forEach(function(prop) {
      if (staticData[prop] !== data[prop]) {
        // Validation error is in mschema error format
        throw [{
          property: prop,
          constraint: 'static',
          expected: staticData[prop],
          actual: data[prop],
          message: 'Data does not match static data'
        }];
      }
    });
    resource.assertValid(data);
  };

  Object.defineProperty(this, 'foreignKeys', {
    get: function() {
      return []
    }
  })

  Object.defineProperty(this, 'hasForeignKey', {
    get: function() {
      return false
    }
  })

  Object.defineProperty(this, 'parent', {
    value: resource,
    writable: false,
    enumerable: true
  });

  Object.defineProperty(this, 'spec', {
    get: function() {
      return resource.spec
    },
    enumerable: true
  });

  Object.defineProperty(this, 'type', {
    value: resource.type,
    writable: false,
    enumerable: true
  });

  Object.defineProperty(this, 'bound', {
    value: true,
    writable: false,
    enumerable: true
  });
}

module.exports = OKResource;