-
Notifications
You must be signed in to change notification settings - Fork 13
/
baas.io.js
2450 lines (2233 loc) · 60.8 KB
/
baas.io.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function() {
var root = this;
var Baas = root.Baas || {};
root.console = root.console || {};
root.console.log = root.console.log || function() {};
// Current version.
Baas.VERSION = '0.9.2';
// AMD 모듈 방식 - require() -과 Node.js 모듈 시스템을 위한 코드
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = Baas;
}
exports.Baas = Baas;
} else {
root.Baas = Baas;
}
/*
* The class models Baas io.
*
* @constructor
* @param {string} options - configuration object
*/
Baas.IO = function(options) {
//usergrid enpoint
this.URI = options.URI || 'https://api.baas.io';
//Find your Orgname and Appname in the Admin portal (http://apigee.com/usergrid)
this.orgName = options.orgName;
this.appName = options.appName;
//other options
this.buildCurl = options.buildCurl || false;
this.logging = options.logging || false;
//timeout and callbacks
this._callTimeout = options.callTimeout || 30000; //default to 30 seconds
this._callTimeoutCallback = options.callTimeoutCallback || null;
this.logoutCallback = options.logoutCallback || null;
};
/*
* Main function for making requests to the API. Can be called directly.
*
* options object:
* `method` - http method (GET, POST, PUT, or DELETE), defaults to GET
* `qs` - object containing querystring values to be appended to the uri
* `body` - object containing entity body for POST and PUT requests
* `endpoint` - API endpoint, for example 'users/fred'
* `mQuery` - boolean, set to true if running management query, defaults to false
*
* @method request
* @public
* @params {object} options
* @param {function} callback
* @return {callback} callback(err, data)
*/
Baas.IO.prototype.request = function (options, callback) {
var self = this;
var method = options.method || 'GET';
var endpoint = options.endpoint;
var body = options.body || {};
var contentType = options.contentType || 'application/json';
var qs = options.qs || {};
var mQuery = options.mQuery || false; //is this a query to the management endpoint?
if (mQuery) {
var uri = this.URI + '/' + endpoint;
} else {
var uri = this.URI + '/' + this.orgName + '/' + this.appName + '/' + endpoint;
}
//if (self.getToken()) {
//qs['access_token'] = self.getToken();
/* //could also use headers for the token
xhr.setRequestHeader("Authorization", "Bearer " + self.getToken());
xhr.withCredentials = true;
*/
//}
//append params to the path
var encoded_params = Baas.Utils.encodeParams(qs);
if (encoded_params) {
uri += "?" + encoded_params;
}
//stringify the body object
//body = (body instanceof FormData) ? body : body;
//20140807 modify
body = (contentType === 'application/json') ? JSON.stringify(body) : body;
//so far so good, so run the query
var xhr = new XMLHttpRequest();
xhr.open(method, uri, true);
if (self.getToken()) {
xhr.setRequestHeader("Authorization", "Bearer " + self.getToken());
}
if(contentType){
xhr.setRequestHeader("Content-Type", contentType);
}
// Handle response.
xhr.onerror = function() {
self._end = new Date().getTime();
if (self.logging) {
console.log('success (time: ' + self.calcTimeDiff() + '): ' + method + ' ' + uri);
}
if (self.logging) {
console.log('Error: API call failed at the network level.')
}
//network error
clearTimeout(timeout);
var err = true;
if (typeof(callback) === 'function') {
callback(err, data);
}
};
xhr.onload = function(response) {
//call timing, get time, then log the call
self._end = new Date().getTime();
if (self.logging) {
console.log('success (time: ' + self.calcTimeDiff() + '): ' + method + ' ' + uri);
}
//call completed
clearTimeout(timeout);
//download file
if(endpoint.indexOf('files/') >= 0 && endpoint.indexOf('/data') >= 0) {callback(false);return;}
//decode the response
response = JSON.parse(xhr.responseText);
if (xhr.status != 200) {
//there was an api error
var error = response.error;
var error_description = response.error_description;
if (self.logging) {
console.log('Error ('+ xhr.status +')(' + error + '): ' + error_description )
}
if ( (error == "auth_expired_session_token") ||
(error == "auth_missing_credentials") ||
(error == "auth_unverified_oath") ||
(error == "expired_token") ||
(error == "unauthorized") ||
(error == "auth_invalid")) {
//these errors mean the user is not authorized for whatever reason. If a logout function is defined, call it
//if the user has specified a logout callback:
if (typeof(self.logoutCallback) === 'function') {
return self.logoutCallback(true, response);
}
}
if (typeof(callback) === 'function') {
callback(true, response);
}
} else {
if (typeof(callback) === 'function') {
callback(false, response);
}
}
};
var timeout = setTimeout(
function() {
xhr.abort();
if (self._callTimeoutCallback === 'function') {
self._callTimeoutCallback('API CALL TIMEOUT');
} else {
self.callback('API CALL TIMEOUT');
}
},
self._callTimeout); //set for 30 seconds
if (this.logging) {
console.log('calling: ' + method + ' ' + uri);
}
if (this.buildCurl) {
var curlOptions = {
uri:uri,
body:body,
method:method
}
this.buildCurlCall(curlOptions);
}
this._start = new Date().getTime();
xhr.send(body);
}
/*
* function for building asset urls
*
* @method buildAssetURL
* @public
* @params {string} uuid
* @return {string} assetURL
*/
/**
* baas.io is not being supported 'buildAssetURL' function.
*/
/*
Baas.IO.prototype.buildAssetURL = function(uuid) {
var self = this;
var qs = {};
var assetURL = this.URI + '/' + this.orgName + '/' + this.appName + '/assets/' + uuid + '/data';
if (self.getToken()) {
qs['access_token'] = self.getToken();
}
//append params to the path
var encoded_params = encodeParams(qs);
if (encoded_params) {
assetURL += "?" + encoded_params;
}
return assetURL;
}
*/
/*
* Main function for creating new groups. Call this directly.
*
* @method createGroup
* @public
* @params {string} path
* @param {function} callback
* @return {callback} callback(err, data)
*/
Baas.IO.prototype.createGroup = function(options, callback) {
var getOnExist = options.getOnExist || false;
var options = {
path: options.path,
client: this,
data:options
}
var group = new Baas.Group(options);
group.fetch(function(err, data){
var okToSave = (err && 'Service resource not found' === data.error_description || 'no_name_specified' === data.error || 'null_pointer' === data.error_description) || (!err && getOnExist);
if (okToSave) {
group.save(function(err){
if (typeof(callback) === 'function') {
callback(err, group);
}
});
} else {
if(typeof(callback) === 'function') {
callback(err, group);
}
}
});
}
/*
* Main function for creating new entities - should be called directly.
*
* options object: options {data:{'type':'collection_type', 'key':'value'}, uuid:uuid}}
*
* @method createEntity
* @public
* @params {object} options
* @param {function} callback
* @return {callback} callback(err, data)
*/
Baas.IO.prototype.createEntity = function (options, callback) {
// todo: replace the check for new / save on not found code with simple save
// when users PUT on no user fix is in place.
/*
var options = {
client:this,
data:options
}
var entity = new Baas.Entity(options);
entity.save(function(err, data) {
if (typeof(callback) === 'function') {
callback(err, entity);
}
});
*/
var getOnExist = options.getOnExist || false; //if true, will return entity if one already exists
var options = {
client:this,
data:options
}
var entity = new Baas.Entity(options);
entity.fetch(function(err, data) {
//if the fetch doesn't find what we are looking for, or there is no error, do a save
var okToSave = (err && 'Service resource not found' === data.error_description || 'no_name_specified' === data.error || 'null_pointer' === data.error_description) || (!err && getOnExist);
if(okToSave) {
entity.set(options.data); //add the data again just in case
entity.save(function(err) {
if (typeof(callback) === 'function') {
callback(err, entity);
}
});
} else {
if (typeof(callback) === 'function') {
callback(err, entity);
}
}
});
}
/*
* Main function for restoring an entity from serialized data.
*
* serializedObject should have come from entityObject.serialize();
*
* @method restoreEntity
* @public
* @param {string} serializedObject
* @return {object} Entity Object
*/
Baas.IO.prototype.restoreEntity = function (serializedObject) {
var data = JSON.parse(serializedObject);
var options = {
client:this,
data:data
}
var entity = new Baas.Entity(options);
return entity;
}
/*
* Main function for getting existing entities - should be called directly.
*
* You must supply a uuid or (username or name). Username only applies to users.
* Name applies to all custom entities
*
* options object: options {data:{'type':'collection_type', 'name':'value', 'username':'value'}, uuid:uuid}}
*
* @method createEntity
* @public
* @params {object} options
* @param {function} callback
* @return {callback} callback(err, data)
*/
Baas.IO.prototype.getEntity = function (options, callback) {
var options = {
client:this,
data:options
}
var entity = new Baas.Entity(options);
entity.fetch(function(err) {
if (typeof(callback) === 'function') {
callback(err, entity);
}
});
}
/*
* Main function for creating new collections - should be called directly.
*
* options object: options {client:client, type: type, qs:qs}
*
* @method createCollection
* @public
* @params {object} options
* @param {function} callback
* @return {callback} callback(err, data)
*/
Baas.IO.prototype.createCollection = function (options, callback) {
options.client = this;
var collection = new Baas.Collection(options, function(err) {
if (typeof(callback) === 'function') {
callback(err, collection);
}
});
}
/*
* Main function for restoring a collection from serialized data.
*
* serializedObject should have come from collectionObject.serialize();
*
* @method restoreCollection
* @public
* @param {string} serializedObject
* @return {object} Collection Object
*/
Baas.IO.prototype.restoreCollection = function (serializedObject) {
var data = JSON.parse(serializedObject);
data.client = this;
var collection = new Baas.Collection(data);
return collection;
}
/*
* Main function for retrieving a user's activity feed.
*
* @method getFeedForUser
* @public
* @params {string} username or uuid or email
* @param {function} callback
* @return {callback} callback(err, data, activities)
*/
Baas.IO.prototype.getFeedForUser = function(username, callback) {
var options = {
method: "GET",
endpoint: "users/"+username+"/feed"
}
this.request(options, function(err, data){
if(typeof(callback) === "function") {
if(err) {
callback(err);
} else {
callback(err, data, data.entities);
}
}
});
}
/*
* Function for creating new activities for the current user - should be called directly.
*
* //user can be any of the following: "me", a uuid, a username
* Note: the "me" alias will reference the currently logged in user (e.g. 'users/me/activties')
*
* //build a json object that looks like this:
* var options =
* {
* "actor" : {
* "displayName" :"myusername",
* "uuid" : "myuserid",
* "username" : "myusername",
* "email" : "myemail",
* "picture": "http://path/to/picture",
* "image" : {
* "duration" : 0,
* "height" : 80,
* "url" : "http://www.gravatar.com/avatar/",
* "width" : 80
* },
* },
* "verb" : "post",
* "content" : "My cool message",
* "lat" : 48.856614,
* "lon" : 2.352222
* }
*
* @method createEntity
* @public
* @params {string} user // "me", a uuid, or a username
* @params {object} options
* @param {function} callback
* @return {callback} callback(err, data)
*/
Baas.IO.prototype.createUserActivity = function (user, options, callback) {
options.type = 'users/'+user+'/activities';
var options = {
client:this,
data:options
}
var entity = new Baas.Entity(options);
entity.save(function(err) {
if (typeof(callback) === 'function') {
callback(err, entity);
}
});
}
/*
* Function for creating user activities with an associated user entity.
*
* user object:
* The user object passed into this function is an instance of Baas.Entity.
*
* @method createUserActivityWithEntity
* @public
* @params {object} user
* @params {string} content
* @param {function} callback
* @return {callback} callback(err, data)
*/
Baas.IO.prototype.createUserActivityWithEntity = function(user, content, callback) {
var username = user.get("username");
var options = {
actor: {
"displayName":username,
"uuid":user.get("uuid"),
"username":username,
"email":user.get("email"),
"picture":user.get("picture"),
"image": {
"duration":0,
"height":80,
"url":user.get("picture"),
"width":80
},
},
"verb":"post",
"content":content };
this.createUserActivity(username, options, callback);
}
/*
* A private method to get call timing of last call
*/
Baas.IO.prototype.calcTimeDiff = function () {
var seconds = 0;
var time = this._end - this._start;
try {
seconds = ((time/10) / 60).toFixed(2);
} catch(e) { return 0; }
return seconds;
}
/*
* A public method to store the OAuth token for later use - uses localstorage if available
*
* @method setToken
* @public
* @params {string} token
* @return none
*/
Baas.IO.prototype.setToken = function (token) {
var tokenKey = 'token' + this.appName + this.orgName;
this.token = token;
if(typeof(Storage)!=="undefined"){
if (token) {
localStorage.setItem(tokenKey, token);
} else {
localStorage.removeItem(tokenKey);
}
}
}
/*
* A public method to get the OAuth token
*
* @method getToken
* @public
* @return {string} token
*/
Baas.IO.prototype.getToken = function () {
var tokenKey = 'token' + this.appName + this.orgName;
if (this.token) {
return this.token;
} else if(typeof(Storage)!=="undefined") {
return localStorage.getItem(tokenKey);
}
return null;
}
/*
* A public facing helper method for signing up users
*
* @method signup
* @public
* @params {string} username
* @params {string} password
* @params {string} email
* @param {function} callback
* @return {callback} callback(err, data)
*/
Baas.IO.prototype.signup = function(username, password, email, callback) {
var options = {
type:"users",
username:username,
password:password,
email:email,
};
this.createEntity(options, callback);
}
/*
* Kakao의 API를 사용하여 Baas.io User Collection에 User를 추가하는 메소드
*
* @method kakao_signup
* @public
* @params {object} kakao_data
* @param {function} callback
*/
Baas.IO.prototype.kakao_signup = function(kakao_data, callback){
var options = {
method:'POST',
endpoint : 'auth/kakaotalk',
contentType : 'application/x-www-form-urlencoded',
token : this.getToken(),
body:'kkt_access_token=' + kakao_data.kkt_access_token
}
this.request(options, callback);
}
/*
* Kakao의 token으로 signin을 할 수 있는 메소드
*
* @method kakao_signup
* @public
* @params {object} kakao_data
* @param {function} callback
*/
Baas.IO.prototype.kakao_signin = function(kakao_data, callback){
this.kakao_signup.apply(this,arguments);
}
/*
* Kakao의 token으로 login을 할 수 있는 메소드
*
* @method kakao_signup
* @public
* @params {object} kakao_data
* @param {function} callback
*/
Baas.IO.prototype.kakao_login = function(kakao_data, callback){
this.kakao_signup.apply(this,arguments);
}
/*
*
* A public method to log in an app user - stores the token for later use
*
* @method login
* @public
* @params {string} username
* @params {string} password
* @param {function} callback
* @return {callback} callback(err, data)
*/
Baas.IO.prototype.login = function (username, password, callback) {
var self = this;
var options = {
method:'POST',
endpoint:'token',
body:{
username: username,
password: password,
grant_type: 'password'
}
};
this.request(options, function(err, data) {
var user = {};
if (err && self.logging) {
console.log('error trying to log user in');
} else {
var options = {
client:self,
data:data.user
}
user = new Baas.Entity(options);
self.setToken(data.access_token);
}
if (typeof(callback) === 'function') {
callback(err, data, user);
}
});
}
/*
* A public method to log in an app user with facebook - stores the token for later use
*
* @method loginFacebook
* @public
* @params {string} username
* @params {string} password
* @param {function} callback
* @return {callback} callback(err, data)
*/
Baas.IO.prototype.loginFacebook = function (facebookToken, callback) {
var self = this;
var options = {
method:'GET',
endpoint:'auth/facebook',
qs:{
fb_access_token: facebookToken
}
};
this.request(options, function(err, data) {
var user = {};
if (err && self.logging) {
console.log('error trying to log user in');
} else {
var options = {
client: self,
data: data.user
}
user = new Baas.Entity(options);
self.setToken(data.access_token);
}
if (typeof(callback) === 'function') {
callback(err, data, user);
}
});
}
/*
* A public method to get the currently logged in user entity
*
* @method getLoggedInUser
* @public
* @param {function} callback
* @return {callback} callback(err, data)
*/
Baas.IO.prototype.getLoggedInUser = function (callback) {
if (!this.getToken()) {
callback(true, null, null);
} else {
var self = this;
var options = {
method:'GET',
endpoint:'users/me',
};
this.request(options, function(err, data) {
if (err) {
if (self.logging) {
console.log('error trying to log user in');
}
if (typeof(callback) === 'function') {
callback(err, data, null);
}
} else {
var options = {
client:self,
data:data.entities[0]
}
var user = new Baas.Entity(options);
if (typeof(callback) === 'function') {
callback(err, data, user);
}
}
});
}
}
/*
* A public method to test if a user is logged in - does not guarantee that the token is still valid,
* but rather that one exists
*
* @method isLoggedIn
* @public
* @return {boolean} Returns true the user is logged in (has token and uuid), false if not
*/
Baas.IO.prototype.isLoggedIn = function () {
if (this.getToken() && this.getToken() != 'null') {
return true;
}
return false;
}
/*
* A public method to log out an app user - clears all user fields from client
*
* @method logout
* @public
* @return none
*/
Baas.IO.prototype.logout = function () {
this.setToken(null);
}
/*
* A private method to build the curl call to display on the command line
*
* @method buildCurlCall
* @private
* @param {object} options
* @return {string} curl
*/
Baas.IO.prototype.buildCurlCall = function (options) {
var curl = 'curl';
var method = (options.method || 'GET').toUpperCase();
var body = options.body || {};
var uri = options.uri;
//curl - add the method to the command (no need to add anything for GET)
if (method === 'POST') {curl += ' -X POST'; }
else if (method === 'PUT') { curl += ' -X PUT'; }
else if (method === 'DELETE') { curl += ' -X DELETE'; }
else { curl += ' -X GET'; }
//curl - append the path
curl += ' ' + uri;
//curl - add the body
if (body !== '"{}"' && method !== 'GET' && method !== 'DELETE') {
//curl - add in the json obj
curl += " -d '" + body + "'";
}
//log the curl command to the console
console.log(curl);
return curl;
}
/*
* A class to Model a Baas Entity.
* Set the type of entity in the 'data' json object
*
* @constructor
* @param {object} options {client:client, data:{'type':'collection_type', 'key':'value'}, uuid:uuid}}
*/
Baas.Entity = function(options) {
if(options){
this._client = options.client;
this._data = options.data || {};
}
};
/*
* returns a serialized version of the entity object
*
* Note: use the client.restoreEntity() function to restore
*
* @method serialize
* @return {string} data
*/
Baas.Entity.prototype.serialize = function () {
return JSON.stringify(this._data);
}
/*
* gets a specific field or the entire data object. If null or no argument
* passed, will return all data, else, will return a specific field
*
* @method get
* @param {string} field
* @return {string} || {object} data
*/
Baas.Entity.prototype.get = function (field) {
if (field) {
return this._data[field];
} else {
return this._data;
}
}
/*
* adds a specific key value pair or object to the Entity's data
* is additive - will not overwrite existing values unless they
* are explicitly specified
*
* @method set
* @param {string} key || {object}
* @param {string} value
* @return none
*/
Baas.Entity.prototype.set = function (key, value) {
if (typeof key === 'object') {
for(var field in key) {
this._data[field] = key[field];
}
} else if (typeof key === 'string') {
if (value === null) {
delete this._data[key];
} else {
this._data[key] = value;
}
} else {
this._data = null;
}
}
/*
* Saves the entity back to the database
*
* @method save
* @public
* @param {function} callback
* @return {callback} callback(err, data)
*/
Baas.Entity.prototype.save = function (callback) {
//TODO: API will be changed soon to accomodate PUTs via name which create new entities
// This function should be changed to PUT only at that time, and updated to use
// either uuid or name
var type = this.get('type');
var method = 'POST';
if (Baas.Utils.isUUID(this.get('uuid'))) {
method = 'PUT';
type += '/' + this.get('uuid');
} else if(type === 'users' && this.get('username')) {
method = 'PUT';
type += '/' + this.get('username');
} else if(this.get('name')){
method = 'PUT';
type += '/' + this.get('name');
}
//update the entity
var self = this;
var data = {};
var entityData = this.get();
//remove system specific properties
for (var item in entityData) {
if (item === 'metadata' || item === 'created' || item === 'modified' ||
item === 'type' || item === 'activated' || item ==='uuid') { continue; }
data[item] = entityData[item];
}
var options = {
method:method,
endpoint:type,
body:data
};
//save the entity first
this._client.request(options, function (err, retdata) {
if (err && self._client.logging) {
console.log('could not save entity');
if (typeof(callback) === 'function') {
return callback(err, retdata, self);
}
} else {
if (retdata.entities) {
if (retdata.entities.length) {
var entity = retdata.entities[0];
self.set(entity);
}
}
//if this is a user, update the password if it has been specified;
var needPasswordChange = (self.get('type') === 'user' && entityData.oldpassword && entityData.newpassword);
if (needPasswordChange) {
//Note: we have a ticket in to change PUT calls to /users to accept the password change
// once that is done, we will remove this call and merge it all into one
var pwdata = {};
pwdata.oldpassword = entityData.oldpassword;
pwdata.newpassword = entityData.newpassword;
var options = {
method:'PUT',
endpoint:type+'/password',
body:pwdata
}
self._client.request(options, function (err, data) {
if (err && self._client.logging) {
console.log('could not update user');
}
//remove old and new password fields so they don't end up as part of the entity object
self.set('oldpassword', null);
self.set('newpassword', null);
if (typeof(callback) === 'function') {
callback(err, data, self);
}
});
} else if (typeof(callback) === 'function') {
callback(err, retdata, self);
}
}
});
}
/*
* refreshes the entity by making a GET call back to the database
*
* @method fetch
* @public
* @param {function} callback
* @return {callback} callback(err, data)
*/
Baas.Entity.prototype.fetch = function (callback) {
var type = this.get('type');
var self = this;
//if a uuid is available, use that, otherwise, use the name
if (this.get('uuid')) {
type += '/' + this.get('uuid');
} else {
if (type === 'users') {
if (this.get('username')) {
type += '/' + this.get('username');
} else {
if (typeof(callback) === 'function') {
var error = 'no_name_specified';
if (self._client.logging) {
console.log(error);
}
return callback(true, {error:error}, self)
}
}
} else if (type === 'a path') {
///TODO add code to deal with the type as a path
if (this.get('path')) {
type += '/' + encodeURIComponent(this.get('name'));
} else {
if (typeof(callback) === 'function') {
var error = 'no_name_specified';
if (self._client.logging) {
console.log(error);
}
return callback(true, {error:error}, self)
}
}