Skip to content

Instantly share code, notes, and snippets.

@karlwestin
Created October 4, 2013 09:38
Show Gist options
  • Select an option

  • Save karlwestin/6823456 to your computer and use it in GitHub Desktop.

Select an option

Save karlwestin/6823456 to your computer and use it in GitHub Desktop.
cors.fake.js Stripping out the 'sync' layer of a backbone app and use a bunch of objects as responses instead
define([
"jquery",
"config",
"tools/filters",
"lib/json2"
], function(
$,
config,
Filters
) {
// THIS IS THE ACTUAL FAKING OF REQUESTS
var responses = {
// hash with responses like
// this could be generated by some panel or something
"http://localhost:8000/s-rfz/api/embedded1/authed/accounts": {
_control: { result: "ok" },
accounts: [
//accounts
]
}
}
function fakeRequest(setup) {
if(responses[setup.url]) {
return $.Deferred.resolve(responses[setup.url]);
}
return $.Deferred.reject({ _control: { result "error" } });
}
// EVERYTHING BELOW HERE IS EXACTLY CORS.SYNC
function checkResult(resp, context, url, data, retries) {
context = context || this;
var result = resp._control && resp._control.result;
if(retries > 9) {
result = "error";
}
switch(result) {
case "ok":
return $.Deferred().resolveWith(context, [resp]).promise();
case "retry":
// for example for polling accounts after PreciseID
++retries;
var pr = $.Deferred();
setTimeout(function() {
corsRequest(url, data, context, retries)
.done(function() { pr.resolveWith(context, arguments); })
.fail(function() { pr.rejectWith(context, arguments); });
}, retries * 2500);
return pr.promise();
default: // implies 'error' as well
return $.Deferred().rejectWith(context, [{}, "fail", resp]).promise();
}
}
function corsRequest(url, data, context, retries) {
data = data || {};
try {
user = require("embed/user/user");
$.extend(data, user.getCredentials());
} catch(e) {}
if(url[0] !== "/") {
url = "/" + url;
}
var setup = {
method: "POST",
url: config.cdn + url,
contentType: 'text/plain',
data: JSON.stringify(data),
dataType : "json"
};
var call = fakeRequest(setup);
return call.then(function(resp) {
return checkResult(resp, context, url, data, retries || 0);
}, function(xhr, err, resp) {
return checkResult(resp, context);
});
}
/*
* Backbone.sync method for cors
* hello insanity
*/
var methods = {
"create": "/create",
"delete": "/delete",
"update": "/update",
"read": ""
};
function sync(method, model, options) {
options = options || {};
var type = methods[method],
// we will need to revise this later on
// for simulation etc
data = (model instanceof Backbone.Model) ? model.toJSON() : {},
url = options.url || model.url;
if(!url) {
throw new Error("Model has no URL");
}
if(typeof url === "function") {
url = model.url();
}
url = url + type;
/*
* filters and converters
* from RPC.sync
*/
// only send specified keys + apiKey and user token
if(model.serverKeys) {
data = _.pick.apply(_, [data].concat(model.serverKeys).concat(["apiKey", "userToken"]));
}
// Preparing/filtering data for saving to server
_.each(model.filter || [], function(key) {
data[key] = Filters.FILTERS.numbersOnly(data[key]);
});
_.each(model.convert || [], function(method, key) {
if(typeof method === "function") {
data[key] = method(data[key]);
} else {
data[key] = Filters.CONVERTERS[method](data[key]);
}
});
var req = corsRequest(url, data, model);
req.then(options.success, options.error);
return req;
}
corsRequest.sync = sync;
return corsRequest;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment