-
Notifications
You must be signed in to change notification settings - Fork 1
/
MongoStore.js
431 lines (417 loc) · 13.3 KB
/
MongoStore.js
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
* dojo.data store supporting MongoQueries.
*
* :requires: Dojo 1.4.x
* :copyright: Gary Bishop, Peter Parente 2010
* :license: BSD
**/
dojo.provide('uow.data.MongoStore');
dojo.require('dojox.rpc.Service');
dojo.require('dojox.rpc.Rest');
dojo.require('dojox.data.JsonRestStore');
dojo.require('dojo.io.iframe');
dojo.declare('uow.data.MongoStore', [dojox.data.JsonRestStore], {
constructor: function(options){
// monkey patch service._getRequest to insert an additional header
if (options.accessKey) {
var _getRequest = this.service._getRequest;
var myKey = options.accessKey;
this.accessKey = myKey;
var myGetRequest = function(id, args) {
var request = _getRequest(id, args);
// take the key off the path before using it.
request.headers['Authorization'] = myKey;
// fix a bug in dojo range handling
if (args && (args.start >= 0 || args.count >= 0)) {
var start = args.start || 0;
var range = 'items=' + start + '-';
if (args.count !== undefined && args.count != Infinity) {
if (args.count === 0) {
// minimum is one because last-pos must be >= than first-pos
// according to 14.35 in http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
range += start;
} else {
range += args.count + start - 1;
}
}
request.headers.Range = range;
}
return request;
};
this.service._getRequest = myGetRequest;
}
},
_doQuery: function(args) {
// pack the query into one parameter with the query args json and uri encoded
// undefined won't json decode, make it an empty query
// shallow copy of args so we don't screw up what got handed in
var Args = {};
dojo.mixin(Args, args);
args = Args;
var qs = {};
if (args.query && typeof(args.query) == 'string') { // fetchItemByIdentity
return this.inherited(arguments);
}
if (args.query && typeof(args.query) == 'object') {
qs.mq = encodeURIComponent(dojo.toJson(args.query));
}
if (args.sort && typeof(args.sort) != 'undefined') {
var s = dojo.map(args.sort, function(v) {
return (v.descending ? '-' : '+') + encodeURIComponent(v.attribute); }).join(',');
qs.ms = s;
}
args.query = qs;
// hand off to the method in JsonRestStore
return this.inherited(arguments);
},
upload: function(args) {
// upload a file using io.iframe.send
// you need to set form, load, and error
args.url = '/Media/upload/';
args.method = 'post';
args.content = { 'Authorization': this.accessKey };
args.handleAs = 'json';
dojo.io.iframe.send(args);
},
getValue: function(item, property, defaultValue){
// taken from http://bugs.dojotoolkit.org/attachment/ticket/7175/BeanStore.js
// summary:
// Gets the value of an item's 'property', supports dot-notation
//
// item: /* object */
// property: /* string */
// property to look up value for
// defaultValue: /* string */
// the default value
if (property.indexOf(".") > 0) { //dot-notation
var matches = property.match(/(\w+)\.([\w\.]+)/);
if (matches && matches.length > 2) {
var association = this.getValue(item, matches[1]);
if (association) {
return this.getValue(association, matches[2]);
}
}
}
else {
return this.inherited(arguments);
}
},
getMode: function() {
// return the permission string actually granted
return this.accessKey.split('-')[0];
},
fetchOne: function(args) {
var def = new dojo.Deferred();
this.fetch({
query : args.query,
onComplete: function(items) {
if(items.length == 1) {
var item = items[0];
def.callback(item);
} else {
def.errback(items.length);
}
},
onError: function(err) {
def.errback(err);
},
scope: this
});
return def;
},
updateOne: function(args) {
var def = new dojo.Deferred();
this.fetchOne(args).then(dojo.hitch(this, function(item) {
for(var attr in args.data) {
// have to use setValue to set dirty flag
this.setValue(item, attr, args.data[attr]);
}
if(args.save) {
this.save({
onComplete: function() {
def.callback(item);
},
onError: function(err) {
def.errback(err);
}
});
} else {
def.callback(item);
}
}), function(err) {
def.errback(err);
});
return def;
},
deleteOne: function(args) {
var def = new dojo.Deferred();
this.fetchOne(args).then(dojo.hitch(this, function(item) {
this.deleteItem(item);
if(args.save) {
this.save({
onComplete: function() {
def.callback(item);
},
onError: function(err) {
def.errback(err);
}
});
} else {
def.callback(item);
}
}), function(err) {
def.errback(err);
});
return def;
},
putOne: function(args) {
var def = new dojo.Deferred();
// fetch success case
this.fetchOne(args).then(dojo.hitch(this, function(item) {
for(var attr in args.data) {
// have to use setValue to set dirty flag
this.setValue(item, attr, args.data[attr]);
}
if(args.save) {
this.save({
onComplete: function() {
def.callback(item);
},
onError: function(err) {
def.errback(err);
}
});
} else {
def.callback(item);
}
}),
// fetch error case
dojo.hitch(this, function(err) {
if(err === 0) {
// create new item from query + data
dojo.mixin(args.data, args.query);
var item = this.newItem(args.data);
if(args.save) {
this.save({
onComplete: function() {
def.callback(item);
},
onError: function(err) {
def.errback(err);
}
});
} else {
def.callback(item);
}
} else {
// more than one match
def.errback(err);
}
}));
return def;
}
});
// Gets a MongoStore instance (like dojox.data.JSONRestStore)
uow.data.getDatabase = function(args) {
var defargs = { idAttribute: '_id',
mode: 'crudO' };
args = args || {};
args = dojo.mixin(defargs, args);
var xhr = {
url: '/data/_auth',
handleAs: 'json',
postData: dojo.toJson({
database: args.database,
collection: args.collection,
mode: args.mode
}),
headers: { "Content-Type": "application/json" }
};
var def = new dojo.Deferred();
dojo.xhrPost(xhr).addCallback(function(response) {
args.target = response.url;
args.accessKey = response.key;
def.callback(new uow.data.MongoStore(args));
}).addErrback(function(err) {
def.errback(err);
});
return def;
};
// Return a store for listing and deleting collections from a database
uow.data.manageDatabase = function(args) {
args = args || {};
return uow.data.getDatabase({
database: args.database,
collection: '*',
mode: 'rd'
});
};
// Ask the server to return the current user
uow.data.getUser = function(args) {
return dojo.xhrGet( {
url: '/data/_auth/user',
handleAs: 'json'
} );
};
// Create an empty collection
uow.data.touchCollection = function(args) {
var def = new dojo.Deferred();
uow.data.getDatabase({
database : args.database,
collection : args.collection
}).then(function(db) {
var item = db.newItem({foo : 'bar'});
//console.log(db.isItem(item));
//console.log(item);
db.save({
onComplete: function() {
//console.log(db.isItem(item));
//console.log(item);
db.deleteItem(item);
db.save({
onComplete: function() {
//console.log('finished delete');
def.callback(db);
},
onError: function() {
//console.log('failed delete');
// error deleting, but collection does exist now
def.callback(db);
}
});
},
onError: function(err) {
def.errback(err);
}
});
}, function(err) {
def.errback(err);
});
return def;
};
// Set the permissions for a user role in a db/collection
uow.data.setAccess = function(args) {
var def = new dojo.Deferred();
uow.data.getDatabase({
database : 'Admin',
collection : 'AccessModes',
mode : 'Ocrud'
}).then(function(db) {
var key = {
database : args.database,
collection : args.collection,
role : args.role
};
if(args.permission === null) {
return db.deleteOne({
query: key,
save: true
});
} else {
return db.putOne({
query : key,
data : {permission : args.permission},
save: true
});
}
}, function(err) {
def.errback(err);
}).then(function(item) {
def.callback(item);
}, function(err) {
def.errback(err);
});
return def;
};
// Set the role for user in a db/collection
uow.data.setRole = function(args) {
var def = new dojo.Deferred();
uow.data.getDatabase({
database : 'Admin',
collection : 'AccessUsers',
mode : 'Ocrud'
}).then(function(db) {
var key = {user : args.user};
if(args.role === null) {
return db.deleteOne({
query: key,
save: true
});
} else {
return db.putOne({
query : key,
data : {role : args.role},
save: true
});
}
}, function(err) {
def.errback(err);
}).then(function(item) {
def.callback(item);
}, function(err) {
def.errback(err);
});
return def;
};
// Set the schema for a db/collection
uow.data.setSchema = function(args) {
var def = new dojo.Deferred();
uow.data.getDatabase({
database : 'Admin',
collection : 'Schemas',
mode : 'Ocrud'
}).then(function(db) {
var key = {
database : args.database,
collection : args.collection
};
if(args.schema === null) {
return db.deleteOne({
query: key,
save: true
});
} else {
return db.putOne({
query : key,
data : {schema : args.schema},
save: true
});
}
}, function(err) {
def.errback(err);
}).then(function(item) {
def.callback(item);
}, function(err) {
def.errback(err);
});
return def;
};
uow.data.warning = function(msg, noAlert) {
if (typeof(msg) === 'object') {
msg = dojo.toJson(msg);
}
function sendWarning(msg, def, retries) {
if (retries <= 0) {
if (!noAlert) {
alert('Please email [email protected] this message: ' + msg);
}
def.errback(msg);
} else {
dojo.xhrPost({
url: '/data/_warning',
handleAs: 'text',
postData: msg,
ioPublish: false,
load: function(resp) {
def.callback(resp);
},
error: function(resp) {
setTimeout(function() { sendWarning(msg, def, retries-1); }, 1000);
}
});
}
}
var def = new dojo.Deferred();
sendWarning(msg, def, 10);
return def;
};