Skip to content

Instantly share code, notes, and snippets.

@yeukhon
Created August 25, 2014 04:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yeukhon/9e6950a5d2d16d621eba to your computer and use it in GitHub Desktop.
Save yeukhon/9e6950a5d2d16d621eba to your computer and use it in GitHub Desktop.
// api.js
var Job = function(settings, jq) {
var createJob = function(args) {
return $.ajax({
url: "https://yeukhon.me/api/job",
type: "POST",
crossDomain: true,
data: {
job_name: args.job_name,
job_type: args.job_type,
options: args.options
}
});
};
// Request handler; every API should have some handlers
var onCreateJobSuccess = function(resp) {
var deferred = $.Deferred();
// resp is already a JSON Object from $.ajax.
// Here we only return the useful data, not including
// resp.status_code, resp.status_text, resp.timestamp, etc
return deferred.reject(resp.data);
};
var onCreateJobFailure = function(xhr) {
// jQuery.fail signature -> jqXHR, textStatus, errorThrown
// I am only interested in the xhr object.
// The API can return 201, 401, 409, 500, even 502, 503 if server
// or service is down (respectively)
var deferred = $.Deferred();
return deferred.reject();
};
// This is the object end-user will use! Job().create({...})
return {
create: function(args, successHandler, failureHandler) {
// we checks to see if args met the minimal requirements
// successHandler and failureHandler are optional (dependcy injection)
return createJob(args).then(successHandler, failureHandler);
}
}
};
// ui.js
// Displays whether the job has been created and ran or not.
var messageWriter = function(data) {
// If job ran, we would get an object with keys like job_id, job_duration, job_result
// Otherwise, we might just write an error message to user explain why
// If status code == 500 we say something wrong with server
// == 502 or 503 we can probably assume service is down
// For now, we will just use .text()
console.log("data is:", data);
$("#resultBoard").text(JSON.stringify(data));
$("#message").text(JSON.stringify(data));
};
// foo yields 409 response
// bar yields 201 response
Job().
create({
job_name: "foo",
job_type: "js"
})
.then(messageWriter);
// Ideally we have many to-do
/*
Job().
create({
job_name: "foo",
job_type: "js"
})
.then(messageWriter)
.then(releaseSubmitButton)
.then(...);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment