| 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
 | // Copyright (C) 2009 BRAT Tech LLC
nglr.DataStore = function(post, users, anchor) {
  this.post = post;
  this.users = users;
  this._cache = {$collections:[]};
  this.anchor = anchor;
  this.bulkRequest = [];
};
nglr.DataStore.prototype.cache = function(document) {
  if (document.constructor != nglr.Model) {
    throw "Parameter must be an instance of Entity! " + nglr.toJson(document);
  }
  var key = document.$entity + '/' + document.$id;
  var cachedDocument = this._cache[key];
  if (cachedDocument) {
    nglr.Model.copyDirectFields(document, cachedDocument);
  } else {
    this._cache[key] = document;
    cachedDocument = document;
  }
  return cachedDocument;
};
nglr.DataStore.prototype.load = function(instance, id, callback, failure) {
  if (id && id !== '*') {
    var self = this;
    this._jsonRequest(["GET", instance.$entity + "/" + id], function(response) {
      instance.$loadFrom(response);
      instance.$migrate();
      var clone = instance.$$entity(instance);
      self.cache(clone);
      (callback||nglr.noop)(instance);
    }, failure);
  }
  return instance;
};
nglr.DataStore.prototype.loadMany = function(entity, ids, callback) {
  var self=this;
  var list = [];
  var callbackCount = 0;
  jQuery.each(ids, function(i, id){
    list.push(self.load(entity(), id, function(){
      callbackCount++;
      if (callbackCount == ids.length) {
        (callback||nglr.noop)(list);
      }
    }));
  });
  return list;
}
nglr.DataStore.prototype.loadOrCreate = function(instance, id, callback) {
  var self=this;
  return this.load(instance, id, callback, function(response){
    if (response.$status_code == 404) {
      instance.$id = id;
      (callback||nglr.noop)(instance);
    } else {
      throw response;
    }
  });
};
nglr.DataStore.prototype.loadAll = function(entity, callback) {
  var self = this;
  var list = [];
  list.$$accept = function(doc){
    return doc.$entity == entity.title;
  };
  this._cache.$collections.push(list);
  this._jsonRequest(["GET", entity.title], function(response) {
    var rows = response;
    for ( var i = 0; i < rows.length; i++) {
      var document = entity();
      document.$loadFrom(rows[i]);
      list.push(self.cache(document));
    }
    (callback||nglr.noop)(list);
  });
  return list;
};
nglr.DataStore.prototype.save = function(document, callback) {
  var self = this;
  var data = {};
  document.$saveTo(data);
  this._jsonRequest(["POST", "", data], function(response) {
    document.$loadFrom(response);
    var cachedDoc = self.cache(document);
    _.each(self._cache.$collections, function(collection){
      if (collection.$$accept(document)) {
        angular.Array.includeIf(collection, cachedDoc, true);
      }
    });
    if (document.$$anchor) {
      self.anchor[document.$$anchor] = document.$id;
    }
    if (callback)
      callback(document);
  });
};
nglr.DataStore.prototype.remove = function(document, callback) {
  var self = this;
  var data = {};
  document.$saveTo(data);
  this._jsonRequest(["DELETE", "", data], function(response) {
    delete self._cache[document.$entity + '/' + document.$id];
    _.each(self._cache.$collections, function(collection){
      for ( var i = 0; i < collection.length; i++) {
        var item = collection[i];
        if (item.$id == document.$id) {
          collection.splice(i, 1);
        }
      }
    });
    (callback||nglr.noop)(response);
  });
};
nglr.DataStore.prototype._jsonRequest = function(request, callback, failure) {
  request.$$callback = callback;
  request.$$failure = failure||function(response){
    throw response;
  };
  this.bulkRequest.push(request);
};
nglr.DataStore.prototype.flush = function() {
  if (this.bulkRequest.length === 0) return;
  var self = this;
  var bulkRequest = this.bulkRequest;
  this.bulkRequest = [];
  console.log('REQUEST:', bulkRequest);
  function callback(code, bulkResponse){
    console.log('RESPONSE[' + code + ']: ', bulkResponse);
    if(bulkResponse.$status_code == 401) {
      self.users.login(function(){
        self.post(bulkRequest, callback);
      });
    } else if(bulkResponse.$status_code) {
      nglr.alert(nglr.toJson(bulkResponse));
    } else {
      for ( var i = 0; i < bulkResponse.length; i++) {
        var response = bulkResponse[i];
        var request = bulkRequest[i];
        var code = response.$status_code;
        if(code) {
          if(code == 403) {
            self.users.notAuthorized();
          } else {
            request.$$failure(response);
          }
        } else {
          request.$$callback(response);
        }
      }
    }
  }
  this.post(bulkRequest, callback);
};
nglr.DataStore.prototype.saveScope = function(scope, callback) {
  var saveCounter = 1;
  function onSaveDone() {
    saveCounter--;
    if (saveCounter === 0 && callback)
      callback();
  }
  for(var key in scope) {
    var item = scope[key];
    if (item && item.$save == nglr.Model.prototype.$save) {
      saveCounter++;
      item.$save(onSaveDone);
    }
  }
  onSaveDone();
};
nglr.DataStore.prototype.query = function(type, query, arg, callback){
  var self = this;
  var queryList = [];
  queryList.$$accept = function(doc){
    return false;
  };
  this._cache.$collections.push(queryList);
  var request = type.title + '/' + query + '=' + arg;
  this._jsonRequest(["GET", request], function(response){
    var list = response;
    for(var i = 0; i < list.length; i++) {
      var document = new type().$loadFrom(list[i]);
      queryList.push(self.cache(document));
    }
    if (callback)
      callback(queryList);
  });
  return queryList;
};
nglr.DataStore.prototype.entities = function(callback) {
  var entities = [];
  var self = this;
  this._jsonRequest(["GET", "$entities"], function(response) {
    for (var entityName in response) {
      entities.push(self.entity(entityName));
    }
    entities.sort(function(a,b){return a.title > b.title ? 1 : -1;});
    if (callback) callback(entities);
  });
  return entities;
};
nglr.DataStore.prototype.documentCountsByUser = function(){
  var counts = {};
  var self = this;
  self.post([["GET", "$users"]], function(code, response){
    jQuery.each(response[0], function(key, value){
      counts[key] = value;
    });
  });
  return counts;
};
nglr.DataStore.prototype.userDocumentIdsByEntity = function(user){
  var ids = {};
  var self = this;
  self.post([["GET", "$users/" + user]], function(code, response){
    jQuery.each(response[0], function(key, value){
      ids[key] = value;
    });
  });
  return ids;
};
nglr.DataStore.NullEntity = function(){};
nglr.DataStore.NullEntity.all = function(){return [];};
nglr.DataStore.NullEntity.query = function(){return [];};
nglr.DataStore.NullEntity.load = function(){return {};};
nglr.DataStore.NullEntity.title = undefined;
nglr.DataStore.prototype.entity = function(name, defaults){
  if (!name) {
    return nglr.DataStore.NullEntity;
  }
  var self = this;
  var entity =  function(initialState){
    return new nglr.Model(entity, initialState);
  };
  // entity.name does not work as name seems to be reserved for functions
  entity.title = name;
  entity.$$factory = true;
  entity.datastore = this;
  entity.defaults = defaults || {};
  entity.load = function(id, callback){
    return self.load(entity(), id, callback);
  };
  entity.loadMany = function(ids, callback){
    return self.loadMany(entity, ids, callback);
  };
  entity.loadOrCreate = function(id, callback){
    return self.loadOrCreate(entity(), id, callback);
  };
  entity.all = function(callback){
    return self.loadAll(entity, callback);
  };
  entity.query = function(query, queryArgs, callback){
    return self.query(entity, query, queryArgs, callback);
  };
  entity.properties = function(callback) {
    self._jsonRequest(["GET", name + "/$properties"], callback);
  };
  return entity;
};
nglr.DataStore.prototype.join = function(join){
  var fn = function(){
    throw "Joined entities can not be instantiated into a document.";
  };
  function base(name){return name ? name.substring(0, name.indexOf('.')) : undefined;}
  function next(name){return name.substring(name.indexOf('.') + 1);}
  var joinOrder = _(join).chain().
    map(function($, name){
      return name;}).
    sortBy(function(name){
      var path = [];
      do {
        if (_(path).include(name)) throw "Infinite loop in join: " + path.join(" -> ");
        path.push(name);
        if (!join[name]) throw _("Named entity '<%=name%>' is undefined.").template({name:name});
        name = base(join[name].on);
      } while(name);
      return path.length;
    }).
    value();
  if (_(joinOrder).select(function($){return join[$].on;}).length != joinOrder.length - 1)
    throw "Exactly one entity needs to be primary.";
  fn.query = function(exp, value) {
    var joinedResult = [];
    var baseName = base(exp);
    if (baseName != joinOrder[0]) throw _("Named entity '<%=name%>' is not a primary entity.").template({name:baseName});
    var Entity = join[baseName].join;
    var joinIndex = 1;
    Entity.query(next(exp), value, function(result){
      var nextJoinName = joinOrder[joinIndex++];
      var nextJoin = join[nextJoinName];
      var nextJoinOn = nextJoin.on;
      var joinIds = {};
      _(result).each(function(doc){
        var row = {};
        joinedResult.push(row);
        row[baseName] = doc;
        var id = nglr.Scope.getter(row, nextJoinOn);
        joinIds[id] = id;
      });
      nextJoin.join.loadMany(_.toArray(joinIds), function(result){
        var byId = {};
        _(result).each(function(doc){
          byId[doc.$id] = doc;
        });
        _(joinedResult).each(function(row){
          var id = nglr.Scope.getter(row, nextJoinOn);
          row[nextJoinName] = byId[id];
        });
      });
    });
    return joinedResult;
  };
  return fn;
};
 |