Skip to content

Instantly share code, notes, and snippets.

@wess
Created February 6, 2012 17:06
Show Gist options
  • Save wess/1753359 to your computer and use it in GitHub Desktop.
Save wess/1753359 to your computer and use it in GitHub Desktop.
Basic and Simple to Use Request Class for CoffeeScript
#
# request.coffee
#
# Created by Wess Cope on 2012-01-30.
#
# Just a start. The basics in place and working
# to expand as elements are needed.
#
class Request
xhrObjects : [
-> new XMLHttpRequest()
-> new ActiveXObject("Msxml2.XMLHTTP")
-> new ActiveXObject("Microsoft.XMLHTTP")
]
request : null
constructor: ->
throw new Error("XMLHttpRequest not supported") if @request?
for request in @xhrObjects
try
requestObject = request()
@request = requestObject
catch err
response: ->
header = @request.getResponseHeader("Content-Type")
text = @request.responseText
if header.indexOf("javascript") >= 0
return eval(text)
else if header.indexOf("json") >= 0
jsonResponse = null
try
jsonResponse = JSON.parse(text)
return jsonResponse
catch err
console.log(err)
return text
parseHeaders: ->
headerObject = {}
headers = @request.getAllResponseHeaders()
leadSpace = /^\s*/
trailSpace = /\s*$/
lines = headers.split("\n")
for line in lines
if line.length == 0
continue
pos = line.indexOf(':')
name = line.substring(0, post).replace(leadSpace, "").replace(trailSpace, "")
value = line.substring((post + 1)).replace(leadSpace, "").replace(trailSpace, "")
headerObject[name] = value
return headerObject
queryString: (params)->
query = new Array
for key, value of params
query.push("%@=%@".$$(key, value))
return query.join("&")
encodeData: (data)->
params = []
for key,value of data
params.push(encodeURIComponent(key) + "=" + encodeURIComponent(value))
return params.join('&')
execute: (method, options)->
throw new Error("No HTTP request method provided") unless method
options ?= {}
throw new Error("No URL was provided") unless options.url
callback = options.callback or (->)
errorCallback = (status, reason, text)->
throw new Error("Status: %@ // Reason: %@ // Description: %@".$$(status, reason, text))
url = options.url
params = options.params ? null
async = options.async ? true
@request.onreadystatechange = (=>
if @request.readyState is 4
if @request.status in [200..240]
callback.apply(@, [@response()])
else
errorCallback.apply(@, [@request.status, @request.statusText, @request.responseText])
)
getParams = "?" + @queryString(params) if params
url = (url + getParams) unless method isnt "GET"
@request.open(method, url, async)
if method is "POST"
@request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
@request.setRequestHeader("X-Request-With", "XMLHttpRequest")
@request.send(@encodeData(params))
else
@request.send(null)
return @response() unless async
get: (options)->
@execute("GET", options)
post: (options)->
@execute("POST", options)
module.exports = Request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment