-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackbone.opensocial.appdatastore.js
231 lines (193 loc) · 8.82 KB
/
backbone.opensocial.appdatastore.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
window.AppDataStore = function(name) {
var that = this;
this.name = name;
this.ids = [];
this.previouslyFetchedFromPipeline = false;
osapi.appdata.get({
fields: [this.name],
escapeType: opensocial.EscapeType.NONE
}).execute(function(response){
if(response.error) {
// TODO: make sure console object exists
console.log("Error " + response.error.code + " retrieving application data: " + response.error.message);
} else if(response && _.keys(response).length == 1) {
var userId = _.keys(response)[0]; // appdata for a user is stored nested under an object with the user's id as the name: {"<user-id>": {"<key-you-requested>":"value"}}
var data = response[userId][that.name]; // get at the actual data
that.ids = (typeof data != 'undefined' && data.split(",")) || []; // split the comma delimited string of IDs into a JS array
} else {
that.ids = []; // something else happened, assume no records exist
}
});
};
window.AppDataStore.Util = {
// Generate four random hex digits.
S4: function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
},
// Generate a pseudo-GUID by concatenating random hexadecimal.
guid: function() {
var S4 = AppDataStore.Util.S4;
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
};
_.extend(AppDataStore.prototype, {
updateIds: function() {
// Convert IDs to key/value JSON
var data = {};
data[this.name] = this.ids.join(",");
// Update appdata with IDs
osapi.appdata.update({data: data}).execute(function(response){
if(response.error) {
console.log("Error " + response.error.code + " updating application data: " + response.error.message);
}
});
},
updateModel: function(model, options) {
options = this._defaultOptions(options);
// Give model a (hopefully)-unique GUID, if it doesn't already
if (!model.id) model.id = model.attributes.id = AppDataStore.Util.guid();
// Convert model to key/value JSON
var data = {};
data[this.name + "-" + model.id] = JSON.stringify(model.toJSON());
// Update appdata with model data
osapi.appdata.update({data: data}).execute(function(response){
if(response.error) {
options.error("Error " + response.error.code + " updating application data: " + response.error.message);
} else {
options.success(response);
}
});
// Update ID store if it doesn't already contain this model's ID
if (!_.include(this.ids, model.id.toString())) {
this.ids.push(model.id.toString());
this.updateIds();
}
},
// Add a model. Same as update(). Here for Backbone API compatiblity
create: function(model, options) { this.updateModel(model, options); },
// Update a model. Same as add(). Here for Backbone API compatiblity
update: function(model, options) { this.updateModel(model, options); },
// Retrieve a model by id.
find: function(model, options) {
options = this._defaultOptions(options);
var that = this;
osapi.appdata.get({
fields: [this.name + "-" + model.id],
escapeType: opensocial.EscapeType.NONE
}).execute(function(response) {
if(response.error) {
options.error("Error " + response.error.code + " retrieving model: " + response.error.message);
} else if(response && _.keys(response).length == 1) {
var userId = _.keys(response)[0];
var data = response[userId][that.name + '-' + model.id];
if(typeof data == 'undefined') {
options.error("Model not found.");
} else {
var object = JSON.parse(data);
options.success(object);
}
} else {
options.error("Model not found.");
}
});
},
// Return the array of all models currently in storage.
findAll: function(options) {
options = this._defaultOptions(options);
var that = this;
// build up a list of all the model keys, so we can find all in one request
var modelKeys = _.map(this.ids, function(id){return that.name + "-" + id; });
// Use data pipelined data if available
if(this.isPipelined()) {
options.success(this.findAllByPipeline());
return;
}
osapi.appdata.get({
fields: modelKeys,
escapeType: opensocial.EscapeType.NONE
}).execute(function(response) {
if(response.error) {
options.error("Error " + response.error.code + " retrieving model: " + response.error.message);
} else if(response && _.keys(response).length == 1) {
var userId = _.keys(response)[0];
// convert each stringified JSON object back into JavaScript and return as an array
var objects = _.map(modelKeys, function(modelKey) { return JSON.parse(response[userId][modelKey]);} )
options.success(objects);
} else {
options.error("Models not found.");
}
});
},
// Delete a model from app data, returning it.
destroy: function(model, options) {
options = this._defaultOptions(options);
// Remove model from AppData
osapi.appdata['delete']({ // use bracket syntax because some browsers think "delete is a keyword"
keys: [this.name + "-" + model.id] // osapi.appdata.delete() uses "keys" instead of "fields" like osapi.appdata.get()
}).execute(function(response) {
if(response.error) {
options.error("Error " + response.error.code + " destroying model: " + response.error.message);
} else {
options.success(model);
}
});
// Update ID store, removing this model's ID
if (_.include(this.ids, model.id.toString())) {
this.ids.push(model.id.toString());
this.ids = _.reject(this.ids, function(id){return id == model.id.toString();});
this.updateIds();
}
},
isPipelined: function() {
if(this.previouslyFetchedFromPipeline == true) return false;
if(typeof opensocial == 'undefined' || typeof opensocial.data == 'undefined') return false;
var dataContext = opensocial.data.getDataContext();
if(typeof dataContext.getDataSet("viewer") == 'undefined' || typeof dataContext.getDataSet("appdata") == 'undefined') return false;
var viewer = dataContext.getDataSet("viewer");
var appdata = dataContext.getDataSet("appdata");
if(typeof appdata[viewer.id][this.name] == 'undefined') {
return false;
} else {
return true;
}
},
findAllByPipeline: function() {
var that = this;
var dataContext = opensocial.data.getDataContext();
var viewer = dataContext.getDataSet("viewer");
var appdata = dataContext.getDataSet("appdata");
// parse initial feed data out of data pipelined data
var idsString = appdata[viewer.id][this.name];
var ids = (typeof idsString == 'undefined' || idsString == "") ? [] : idsString.split(',');
ids = _.reject(ids, function(id) { return id == "" }); // eliminate any empty string ids
var objects = _.map(ids, function(id) {
return JSON.parse(appdata[viewer.id][that.name + "-" + id]);
});
this.previouslyFetchedFromPipeline = true;
return objects;
},
_defaultOptions: function(options) {
options = options || {};
options.success = options.success || function() {};
options.error = options.error || function() {};
return options;
},
});
// Override `Backbone.sync` to use delegate to the model or collection's
// *appDataStorage* property, which should be an instance of `AppDataStore`.
Backbone.sync = function(method, model, options, error) {
// Backwards compatibility with Backbone <= 0.3.3
if (typeof options == 'function') {
options = {
success: options,
error: error
};
}
var store = model.appDataStorage || model.collection.appDataStorage;
switch (method) {
case "read" : model.id ? store.find(model, options) : store.findAll(options); break;
case "create" : store.create(model, options); break;
case "update" : store.update(model, options); break;
case "delete" : store.destroy(model, options); break;
}
};