Skip to content

Instantly share code, notes, and snippets.

@maxtaco
Created July 20, 2014 01:26
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 maxtaco/2683cbc3379a95b6703f to your computer and use it in GitHub Desktop.
Save maxtaco/2683cbc3379a95b6703f to your computer and use it in GitHub Desktop.
Adapter to use jQuery's ajax with IcedCoffeeScript
#-----------------------------------
# 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
#-----------------------------------
@maxtaco
Copy link
Author

maxtaco commented Jul 20, 2014

Now you can call this kind of like:

await $.postal { url : "http://foo.com" }, defer err, data

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment