summaryrefslogtreecommitdiff
path: root/app/node_modules/okresource/index.js
blob: df896176982065faaf96df1ff3b592f9dcf65306 (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
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;
  this._db = options.db;
  this._schema = schema;

  // Define properties which are part of the API

  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
  });
}

/**
 * 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);;
    }
  });
};

/**
 * Update all resources with the given ids with the given data
 */
OKResource.prototype.updateBatch = function(ids, datas) {
  // var type = this.type;
  // var db = this._db;
  // var idField = this.idField;
  // return Q.promise(function(resolve, reject) {
  //   if (!ids || !ids.length || !datas || !datas.length ||
  //       ids.length !== datas.length) {
  //     reject(new Error('Bad input'));
  //   } else {
  //     var queries = ids.map(function(id, i) {
  //       var query = {};
  //       query[idField] = datas[i][idField];
  //       return query;
  //     });
  //     db.putAll(type, queries, datas).then(resolve).fail(reject);
  //   }
  // });
};

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
  });
};

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, '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;