-
Notifications
You must be signed in to change notification settings - Fork 6
/
ParseServices.js
96 lines (76 loc) · 2.47 KB
/
ParseServices.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
angular.module('ParseServices', [])
.factory('ParseSDK', function(){
//initialize parse
Parse.initialize("bHFg1WL11No24JnQ52lKsXoiYXOJnfJUXhEizUZD", "b9mkopWAE3pnEFQ3GSnHaLIxMNhcbnUF02gsgPZ8");
})
.factory('ParseQuery', ['$q', '$rootScope', function ($q, $rootScope){
return function(query, options){
var defer = $q.defer();
//default function call to find
var functionToCall = 'find';
if(options != undefined && options.functionToCall != undefined)
functionToCall = options.functionToCall;
console.log(functionToCall, query);
//wrap defer resolve/reject in $apply so angular updates watch listeners
var defaultParams = [{
success: function(data){
$rootScope.$apply(function(){
defer.resolve(data);
});
},
error: function(data, error){
console.log('error:', error);
$rootScope.$apply(function(){
defer.reject(error);
});
}
}];
//check for additional parameters to add
if(options && options.params)
defaultParams = options.params.concat(defaultParams);
query[functionToCall].apply(query, defaultParams);
return defer.promise;
}
}])
.factory('ParseObject', ['ParseQuery', function(ParseQuery){
return function (parseData, fields){
//verify parameters
if(parseData == undefined) throw new Error('Missing parseData');
if(fields == undefined) throw new Error('Missing fields.');
//internal parse object reference
var parseObject = parseData;
var model;
//instantiate new parse object from string
if(typeof parseData == 'string')
{
var ParseModel = Parse.Object.extend(parseData);
parseObject = new ParseModel();
}
//expose underlying parse obejct through data property
Object.defineProperty(this, 'data', { get : function(){ return parseObject; } });
//add dynamic properties from fields array
var self = this;
for(var i=0; i<fields.length; i++)
{
//add closure
(function() {
var propName = fields[i];
Object.defineProperty(self, propName, {
get : function(){ return parseObject.get(propName); },
set : function(value){ parseObject.set(propName, value); }
});
})();
}
//instance methods
this.save = function(){
return ParseQuery(parseObject, {functionToCall:'save', params:[null]})
}
this.delete = function(){
return ParseQuery(parseObject, {functionToCall:'destroy'});
}
this.fetch = function(){
return ParseQuery(parseObject, {functionToCall:'fetch'});
}
};
}])
;