summaryrefslogtreecommitdiff
path: root/app/node_modules/okresource/index.js
blob: 58b94c275d4d44bcaa18be76f2a39b267aefa3dd (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
var OKRestEndpoint = require('okrest');

/**
 * Creates an OKResource types
 * Takes a resource name and a spec defining the resources attributes.
 */
function createResourceClass(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');
  var type = options.type;
  var schema = options.schema;
  // All resources have the same default CRUD endpoint
  var viewClass = options.endpoint || OKRestEndpoint;
  // Id determines specific resource referenced.
  // Defaults to set of all resources of this type.
  var id = options.id || '*';
  if (viewClass !== OKRestEndpoint && !(viewClass instanceof OKRestEndpoint))
    throw new Error('Resource view not descendent of OKRestEndpoint');

  /**
   * OKResource!
   */
  function OKResource(options) {
    if (!(this instanceof OKResource)) return new OKResource(options);
    if (!options.db)
      throw new Error('No DB provided to OKResource');
    options = options || {};
    this.name = name;
    this._db = options.db;
    this._schema = schema;
  }

  /**
   * Returns the resource's CRUD view
   * This allows us to specify custom views per resource if need be
   */
  OKResource.prototype.view = function(options) {
    return viewClass(this, options);
  };

  OKResource.prototype.assertValid = function(data) {
    this._schema.assertValid(data);
  }

  // Expose the resource type on the class constructor
  Object.defineProperty(OKResource, 'type', {
    value: type,
    writable: false
  });

  return OKResource;
}

module.exports = createResourceClass;