forked from neebz/backbone-parse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backbone-parse.js
108 lines (88 loc) · 2.7 KB
/
backbone-parse.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
/********** PARSE SERVER ACCESS PARAMETERS **********/
var appId = "myApp";
var serverURL = "http://localhost:1337/parse";
/******************* END *************************/
{
/*
Modify each model's parse method to filter
"createdAt" and "updatedAt" returned by parse
*/
let ParseModel = {
parse: function(resp, options) {
delete resp.createdAt;
delete resp.updatedAt;
return resp;
},
idAttribute: "objectId"
};
_.extend(Backbone.Model.prototype, ParseModel);
/*
Replace the parse method of Backbone.Collection
Backbone Collection expects to get a JSON array when fetching.
Parse returns a JSON object with key "results" and value being the array.
*/
let ParseCollection = {
parse : function(resp, options) {
let _parse_class_name = this.__proto__._parse_class_name;
// if the collection is a parse collection and the response is coming from parse server
if (_parse_class_name && resp.results) {
// return array of results from the results property of the response
return resp.results;
} else {
//return original, in case there are collections from another source
return resp;
}
}
};
_.extend(Backbone.Collection.prototype, ParseCollection);
/*
Method to HTTP Type Map
*/
let methodMap = {
'create': 'POST',
'update': 'PUT',
'delete': 'DELETE',
'read': 'GET'
};
/*
Override the default Backbone.sync
*/
let ajaxSync = Backbone.sync;
Backbone.sync = function(method, model, options) {
let object_id = model.models? "" : model.id; //get id if it is not a Backbone Collection
let class_name = model.__proto__._parse_class_name;
if (!class_name) {
return ajaxSync(method, model, options) //It's a not a Parse-backed model, use default sync
}
// create request parameters
let type = methodMap[method];
options || (options = {});
let base_url = serverURL + "/classes";
let url = base_url + "/" + class_name + "/";
if (method != "create") {
url = url + object_id;
}
//Setup data
let data;
if (!options.data && model && (method == 'create' || method == 'update')) {
data = JSON.stringify(model.toJSON());
} else if (options.query && method == "read") { //query for parse objects
data = encodeURI("where=" + JSON.stringify(options.query));
}
let request = {
//data
contentType: "application/json",
processData: false,
dataType: 'json',
data: data,
//action
url: url,
type: type,
//authentication
headers: {
"X-Parse-Application-Id": appId,
}
};
return $.ajax(_.extend(options, request));
};
}