-
Notifications
You must be signed in to change notification settings - Fork 10
/
tiparsejs_wrapper.js
358 lines (333 loc) · 11.9 KB
/
tiparsejs_wrapper.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
const REQUEST_ATTEMPT_LIMIT = 5;
/**
* CommonJS Module Wrapper for TiParseJSSDK
* Get it here:
*
* Original Credits go to:
* twitter: @aaronksaunders
* https://gist.github.com/aaronksaunders/6665528
*/
var TiParse = function(_options) {
// UPDATED TO LATEST PARSE LIBRARY
Parse = require("TiParseJS");
// //FACEBOOK - If you don't need facebook comment out these lines
// TiFacebook = require('facebook');
// TiFacebook.appid = _options.facebookAppId;
//
// FB = {
// provider : {
//
// authenticate : function(_options) {
// var self = this;
// TiFacebook.forceDialogAuth = false;
// TiFacebook.authorize();
//
// TiFacebook.addEventListener('login', function(response) {
//
// if (response.success) {
// if (_options.success) {
// _options.success(self, {
// id : JSON.parse(response.data).id,
// access_token : TiFacebook.accessToken,
// expiration_date : (new Date(TiFacebook.expirationDate)).toJSON()
// });
//
// }
// } else {
// if (_options.error) {
// _options.error(self, response);
// }
// }
// });
//
// },
// restoreAuthentication : function(authData) {
// var authResponse;
// if (authData) {
// authResponse = {
// userID : authData.id,
// accessToken : authData.access_token,
// expiresIn : (Parse._parseDate(authData.expiration_date).getTime() - (new Date()).getTime()) / 1000
// };
// } else {
// authResponse = {
// userID : null,
// accessToken : null,
// expiresIn : null
// };
// }
// //FB.Auth.setAuthResponse(authResponse);
// if (!authData) {
// TiFacebook.logout();
// }
// return true;
// },
// getAuthType : function() {
// return "facebook";
// },
// deauthenticate : function() {
// this.restoreAuthentication(null);
// }
// },
// init : function() {
// Ti.API.debug("called FB.init()");
// },
// login : function() {
// Ti.API.debug("called FB.login()");
// },
// logout : function() {
// Ti.API.debug("called FB.logout()");
// }
// };
/**
Save Eventually - Work in Progress!
Credits to: https://github.com/francimedia/parse-js-local-storage
My version: https://gist.github.com/nitrag/57514857e78bb71bdf23
Example:
var TestObject = Parse.Object.extend("Test");
var testObject = new TestObject();
testObject.set('foo', 'bar1234');
Parse.saveEventually.save("Test", testObject);
fires via a button click
function saveNow(){
if(Ti.Network.online){
if(Parse.saveEventually.sendQueue())
Parse.saveEventually.clearQueue();
}
}
**/
Parse.saveEventually = {
localStorageKey: "Parse.saveEventually.Queue",
initialize: function () {
},
save: function (objectType, object) {
this.addToQueue('save', objectType, object);
},
addToQueue: function (action, objectType, object) {
var queueData = this.getQueue();
// create queueId to avoid duplicates. Maintain previously saved data.
var queueId = ([objectType, object.id, object.get('hash')]).join('_');
var i = this.queueItemExists(queueData, queueId);
if(i > -1) {
for (var prop in queueData[i].data) {
if(object.get(prop) == 'undefined') {
object.set(prop, queueData[i].data[prop]);
}
}
} else {
i = queueData.length;
}
queueData[i] = {
queueId: queueId,
type: objectType,
action: action,
id: object.id,
hash: object.get('hash'),
createdAt: new Date(),
data: object
};
this.setQueue(queueData);
},
getQueue: function () {
var q = Parse.localStorage.getItem(this.localStorageKey) || null;
if(q && (typeof JSON.parse(q) == 'object'))
return JSON.parse(q);
else
return [];
},
setQueue: function (queueData) {
Parse.localStorage.setItem(this.localStorageKey, JSON.stringify(queueData));
},
clearQueue: function () {
Parse.localStorage.setItem(this.localStorageKey, JSON.stringify([]));
},
queueItemExists: function(queueData, queueId) {
for (var i = 0; i < queueData.length; i++) {
if(queueData[i].queueId == queueId) {
return i;
}
};
return -1;
},
countQueue: function(){
return this.getQueue().length;
},
sendQueue: function () {
var queueData = this.getQueue();
if(queueData.length < 1)
return false;
for (var i = 0; i < queueData.length; i++) {
var myObjectType = Parse.Object.extend(queueData[i].type);
// if object has a parse data id, update existing object
if (queueData[i].id) {
this.reprocess.byId(myObjectType, queueData[i]);
}
// if object has no id but a unique identifier, look for existing object, update or create new
else if (queueData[i].hash) {
this.reprocess.byHash(myObjectType, queueData[i]);
}
// else create a new object
else {
this.reprocess.create(myObjectType, queueData[i]);
}
}
return true;
// empty queue - 2do: verify queue has been sent
// this.clearQueue();
},
sendQueueCallback: function (myObject, queueObject) {
switch (queueObject.action) {
case 'save':
// queued update was overwritten by other request > do not save
if (typeof myObject.updatedAt != 'undefined' && myObject.updatedAt > new Date(queueObject.createdAt)) {
return false;
}
myObject.save(queueObject.data, {
success: function (object) {
Ti.API.debug(object);
},
error: function (model, error) {
Ti.API.error(error);
}
});
break;
case 'delete':
// 2do: code to delete queued objects
break;
}
},
reprocess: {
create: function (myObjectType, queueObject) {
var myObject = new myObjectType();
Parse.saveEventually.sendQueueCallback(myObject, queueObject);
},
byId: function (myObjectType, queueObject) {
var query = new Parse.Query(myObjectType);
query.get(queueObject.id, {
success: function (myObject) {
// The object was retrieved successfully.
Parse.saveEventually.sendQueueCallback(myObject, queueObject);
},
error: function (myObject, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and description.
}
});
},
byHash: function (myObjectType, queueObject) {
var query = new Parse.Query(myObjectType);
query.equalTo("hash", queueObject.hash);
query.find({
success: function (results) {
// The object was retrieved successfully.
if(results.length > 0) {
Parse.saveEventually.sendQueueCallback(results[0], queueObject);
}
// The object was not found, create a new one
else {
Parse.saveEventually.reprocess.create(myObjectType, queueObject);
}
},
error: function (myObject, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and description.
}
});
}
}
};
/**
* promise run & error helper
* @param {Number} _options.retry : retry limit
*/
Parse.pCloud = {
initialize: function () {
},
run: function (_fnName, _arguments, _options) {
_options || (_options = {});
var deferred = require('q').defer();
_options.deferred = deferred;
// retryLeft
_options.retryLeft = _.isNumber(_options.retry) ? _options.retry : REQUEST_ATTEMPT_LIMIT;
// default information
var APP = require("core");
_arguments.clientInfo = {
device: APP.Device,
user: {
id: APP.UserM && APP.UserM.id
},
application: {
id: APP.ID,
version: APP.VERSION,
cVersion: APP.CVERSION,
dbVersion : APP.DBVersion,
language : APP.currentLanguage
}
};
// require("core").log('debug', 'Parse.hCloud.run / ' + _fnName + ' : ' + JSON.stringify(_arguments));
this.runner(_fnName, _arguments, _options);
return deferred.promise;
},
runner: function(_fnName, _arguments, _options) {
var that = this;
// network is offline
if (!Ti.Network.online) {
Ti.Network.addEventListener("change", function(e) {
if (e.online) {
Ti.Network.addEventListener("change", arguments.callee);
that.runner(_fnName, _arguments, _options);
}
});
return;
}
var deferred = _options.deferred;
Parse.Cloud.run(_fnName, _arguments, {
success: require("utilities").tryCatcher(function (result) {
// require("core").log('debug', 'Parse.hCloud.run / ' + _fnName + ' : ' + JSON.stringify(result));
_options && _.isFunction(_options.success) && _options.success(result);
deferred.resolve(result);
}),
error: function (error) {
require("core").log('error', 'Parse.hCloud.run / ' + _fnName + ' / retry left ' + _options.retryLeft + ' : ' + JSON.stringify(error));
// 124 : RequestTimeout, 100 : ConnectionFailed
if (!_options.retryLeft || _options.retryLeft <= 0 || (error.code != 124 && error.code > 100)) {
_options && _.isFunction(_options.error) && _options.error(error);
deferred.reject(error);
} else {
// retry
_options.retryLeft--;
// Exponentially-growing random delay
var delay = Math.round(
Math.random() * 125 * Math.pow(2, (REQUEST_ATTEMPT_LIMIT - _options.retryLeft))
);
setTimeout(function() {
that.runner(_fnName, _arguments, _options);
}, delay);
}
}
});
}
};
//
// Enter appropriate parameters for initializing Parse
//
// _options.applicationId, _options.javascriptkey);
//
Parse.initialize(_options.applicationId, _options.javascriptkey);
Parse.serverURL = Ti.App.Properties.getString('Parse_ServerUrl');
//Use Custom Server
//Parse.serverURL = 'http://offroadtrailguide-parse.elasticbeanstalk.com';
// //
// // IF the appid was set for facebook then initialize facebook. if you are going
// // to use Facebook, set the appid at the top of this file
// //
// if (TiFacebook.appid) {
// Parse.FacebookUtils.init({
// appId : TiFacebook.appid, // Facebook App ID
// status : false, // check login status
// cookie : true, // enable cookies to allow Parse to access the session
// xfbml : true // parse XFBML
// });
// }
};
module.exports = TiParse;