Created
July 20, 2014 01:26
-
-
Save maxtaco/2683cbc3379a95b6703f to your computer and use it in GitHub Desktop.
Adapter to use jQuery's ajax with IcedCoffeeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#----------------------------------- | |
# Like postal, but returns like request() on node. | |
$.postal = ({ url, params, dataType, ok_http_status_codes, ok_json_status_codes, ok_empty_body}, cb) -> | |
headers = {} | |
if (t = window.csrf_token)? and t.length | |
headers["X-CSRF-Token"] = t | |
ok_http_status_codes or= [ 200 ] | |
ok_json_status_codes or= [ 'OK' ] | |
#------------- | |
success = (body, status, jqXHR) -> finish true, body, jqXHR | |
error = (jqXHR, textStatus, errorThrown) -> finish false, null, jqXHR | |
#------------- | |
finish = (success, body, jqXHR) -> | |
return unless (tmp = cb)? | |
cb = null | |
err = null | |
out = | |
body : null | |
http_status : null | |
json_status : null | |
if (out.http_status = jqXHR.status)? and (out.http_status in ok_http_status_codes) | |
if not body? | |
err = new Error "empty body sent back from server" if not ok_empty_body | |
else if not (out.json_status = body.status?.name)? or not (out.json_status in ok_json_status_codes) | |
msg = "Server failure" | |
if (d = body?.status?.desc) then msg += ": #{d}" | |
err = new Error msg | |
else | |
out.body = body | |
else | |
msg = "error in POST" | |
if out.http_status? then msg += " (HTTP code #{out.http_status})" | |
err = new Error msg | |
tmp err, out | |
#------------- | |
params = { | |
type : "POST" | |
success | |
error | |
url | |
data : params | |
headers | |
dataType | |
} | |
#------------- | |
$.ajax params | |
#----------------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now you can call this kind of like: