Skip to content

Instantly share code, notes, and snippets.

@crtr0
Created June 15, 2012 19:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save crtr0/2938355 to your computer and use it in GitHub Desktop.
Save crtr0/2938355 to your computer and use it in GitHub Desktop.
Win8 JS library boilerplate for REST services
(function (globals) {
var
// The username and password for BASIC auth
username,
password,
// CHANGE THIS
apiRoot = "https://api.foo.com/version",
get = function (url, params, success, error) {
var queryStr = "";
if (params !== null) {
queryStr = "?"
Object.keys(params).forEach(function (key, i) {
if (i !== 0) { queryStr = queryStr + "&"; }
queryStr = queryStr + key + "=" + encodeURIComponent(params[key]);
});
}
WinJS.xhr({ user: username, password: password, url: url + queryStr }).then(
function (request) {
if (typeof success === "function") {
success(JSON.parse(request.responseText));
}
},
function (request) {
if (typeof error === "function") {
error(JSON.parse(request.responseText));
}
}
);
},
post = function (url, dataHash, success, error) {
var dataStr = "";
Object.keys(dataHash).forEach(function (key, i) {
if (i !== 0) { dataStr = dataStr + "&"; }
dataStr = dataStr + key + "=" + encodeURIComponent(dataHash[key]);
});
WinJS.xhr({
type: "post", user: username, password: password, url: url,
headers: { "Content-type": "application/x-www-form-urlencoded" },
data: dataStr
}).then(
function (request) {
if (typeof success === "function") {
success(JSON.parse(request.responseText));
}
},
function (request) {
if (typeof success === "function") {
error(JSON.parse(request.responseText));
}
}
);
},
// CHANGE "foo"
foo = globals.foo = {};
/* These are the wrappers for the Twilio REST API */
foo.auth = function (u, p) {
username = u;
password = p;
};
foo.restApiCall = function (param1, param2, success, error) {
post(apiRoot + "/path/to/resource", { param1: param1, param2: param2 }, success, error );
};
}(window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment