public
Last active

SproutCore Rails DataSource

  • Download Gist
model.js
JavaScript
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
MyApp.MyModel.mixin({
 
resourcePathFor: function(action, storeKey, item) {
var id, path;
id = storeKey ? MyApp.store.idFor(storeKey) : null;
 
switch(action) {
case 'fetch':
case 'create':
path = 'items';
break;
case 'retrieve':
case 'update':
case 'destroy':
path = 'items/'+id;
}
 
return path;
},
 
resourceBaseParam: 'item',
 
resourceParamsFor: function(action) {
var params = "attr1 attr2".w();
if (action == 'create') params.push('guid');
return params;
}
 
});
rails_data_source.js
JavaScript
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
/** @class TODO: Describe Class
@extends SC.DataSource
@since SproutCore 1.0
*/
 
// For testing
SC.DISABLE_REMOTE_REQUESTS = NO;
 
SC.RailsDataSource = SC.DataSource.extend( {
 
_resourcePathFormat: '/sc/%@.json%@',
 
getFullResourcePath: function(resourcePath, queryParams) {
var params = '';
 
if (queryParams) {
var i = 0;
 
for (var key in queryParams) {
if (queryParams.hasOwnProperty(key)) {
params += '%@%@=%@'.fmt(i === 0 ? '?' : '&', key, queryParams[key]);
i++;
}
}
}
 
return this._resourcePathFormat.fmt(resourcePath, params);
},
 
 
// STANDARD DATA SOURCE METHODS //
 
fetch: function(store, query) {
var recordType = query.recordType || query.recordTypes[0];
var url = this.getFullResourcePath(recordType.resourcePathFor('fetch'));
 
var fetchParams = { query: query, store: store };
 
if (!SC.DISABLE_REMOTE_REQUESTS) {
return NO;
} else {
SC.Request.getUrl(url).set('isJSON', YES)
.notify(this, this._didFetchRecords, fetchParams)
.send();
 
return YES; // Not necessary, but good form
}
},
 
retrieveRecord: function(store, storeKey, id) {
// map storeKey back to record type
var recordType = SC.Store.recordTypeFor(storeKey);
var url = this.getFullResourcePath(recordType.resourcePathFor('retrieve', storeKey));
 
var retrieveParams = { store: store, storeKey: storeKey };
 
if (SC.DISABLE_REMOTE_REQUESTS) {
return NO;
} else {
SC.Request.getUrl(url).set('isJSON', YES)
.notify(this, this._didRetrieveRecord, retrieveParams)
.send();
 
return YES;
}
},
 
createRecord: function(store, storeKey, params) {
var dataHash = store.readDataHash(storeKey),
recordType = SC.Store.recordTypeFor(storeKey),
obj = this._dataToParams(recordType, 'create', dataHash);
 
var url = this.getFullResourcePath(recordType.resourcePathFor('create', storeKey, dataHash));
 
var createParams = { store: store, storeKey: storeKey };
 
if (SC.DISABLE_REMOTE_REQUESTS) {
this._didCreateRecord(null, createParams);
} else {
SC.Request.postUrl(url).set('isJSON', YES)
.header('X-Requested-With', 'XMLHttpRequest')
.notify(this, this._didCreateRecord, createParams)
.send(obj);
}
 
return YES ;
},
 
updateRecord: function(store, storeKey, params) {
if(!params) params = {};
 
var id = store.idFor(storeKey),
dataHash = store.readDataHash(storeKey),
recordType = SC.Store.recordTypeFor(storeKey),
obj = this._dataToParams(recordType, 'update', dataHash),
request;
 
var url = this.getFullResourcePath(recordType.resourcePathFor('update', storeKey));
 
var updateParams = { store: store, storeKey: storeKey };
 
if (!SC.DISABLE_REMOTE_REQUESTS) {
// Send request unless disabled
request = SC.Request.putUrl(url).set('isJSON', YES).header('X-Requested-With', 'XMLHttpRequest');
// Don't notify if skipping response
if (!params.skipResponse) request.notify(this, this._didUpdateRecord, updateParams);
request.send(obj);
}
 
if (SC.DISABLE_REMOTE_REQUESTS || params.skipResponse) {
// Don't wait for a server response
this._didUpdateRecord(null, updateParams);
}
 
return YES ;
},
 
destroyRecord: function(store, storeKey, params) {
if (!params) params = {};
 
var status = store.readStatus(storeKey);
 
if (status === SC.Record.DESTROYED_CLEAN) {
 
// Already clean - probably from calling destroy on a new record
// Is there a better place to handle this?
store.removeDataHash(storeKey, status);
store.dataHashDidChange(storeKey);
 
} else {
 
// Destroy normally
var id = store.idFor(storeKey),
recordType = SC.Store.recordTypeFor(storeKey),
notifyParams = { store: store, storeKey: storeKey };
 
var url = this.getFullResourcePath(recordType.resourcePathFor('destroy', storeKey));
 
if (params.noRequest || SC.DISABLE_REMOTE_REQUESTS) {
this._didDestroyRecord(null, notifyParams);
} else {
SC.Request.deleteUrl(url)
.header('X-Requested-With', 'XMLHttpRequest')
.notify(this, this._didDestroyRecord, notifyParams).send();
}
}
 
return YES ;
},
cancel: function(store, storeKeys) {
return NO;
},
 
_didFetchRecords: function(response, params) {
var store = params.store,
query = params.query,
results = response.get('response'),
resultItem, cleanedResults= [], obj;
 
if (SC.$ok(response)) {
for(idx=0; idx < results.length; idx++) {
resultItem = results[idx];
 
// Hackish way to ignore key
for (var k in resultItem) {
obj = resultItem[k]; break;
}
 
cleanedResults.push(obj);
}
 
// load the contacts into the store...
store.loadRecords(params.recordTypes, cleanedResults);
 
// notify store that we handled the fetch
store.dataSourceDidFetchQuery(query);
} else {
// handle error case
store.dataSourceDidErrorQuery(query, response);
}
},
 
_didRetrieveRecord: function(response, params) {
var store = params.store,
storeKey = params.storeKey,
results = response.get('response'),
cleanedResults;
 
if (SC.$ok(response)) {
// normal: load into store...response == dataHash
 
// Get first item
for (var k in results) {
cleanedResults = results[k]; break;
}
store.dataSourceDidComplete(storeKey, cleanedResults, cleanedResults.id);
} else {
// error: indicate as such...response == error
this._processError(storeKey, response);
}
},
 
_didCreateRecord: function(response, params) {
var results = response && response.get('response'),
storeKey = params.storeKey,
store = params.store,
resultsKeys= [], cleanedResults;
 
if (!response) {
// Request was skipped, pretend it succeeded
store.dataSourceDidComplete(storeKey);
} else if (SC.$ok(response)) {
for(var k in results) resultsKeys.push(k);
cleanedResults = results[resultsKeys[0]];
 
store.dataSourceDidComplete(storeKey, cleanedResults, cleanedResults.id);
} else this._processError(storeKey, response);
},
 
_didUpdateRecord: function(response, params){
var storeKey = params.storeKey,
store = params.store;
 
if (SC.$ok(response)) {
store.dataSourceDidComplete(storeKey);
} else this._processError(storeKey, response);
},
 
_didDestroyRecord: function(response, params){
var storeKey = params.storeKey,
store = params.store;
 
// Response will be null if no actual request made and SC.$ok will still evaluate true
// This is fine since we want to pretend we succeeded anyway
if (SC.$ok(response)) {
store.dataSourceDidDestroy(storeKey);
} else this._processError(storeKey, response);
},
 
_processError: function(storeKey, response) {
var status = response.get('status');
 
if (status === 401) { // Unauthorized
SC.AlertPane.error("Not signed in", "You are not signed in. Please sign in again.");
}
 
store.dataSourceDidError(storeKey, response);
},
 
_dataToParams: function(recordType, action, data) {
var resourceParams = recordType.resourceParamsFor(action),
baseParam = recordType.resourceBaseParam,
cleanedData = {}, item;
 
cleanedData[baseParam] = {};
 
for (v in data) {
item = data[v];
if(resourceParams.indexOf(v) != -1 && item != null) {
if(item == true) item = 1;
if(item == false) item = 0;
cleanedData[baseParam][v] = item;
}
}
 
return cleanedData;
}
 
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.