Skip to content

Instantly share code, notes, and snippets.

@switz
Created November 16, 2012 04:19
Show Gist options
  • Save switz/4084014 to your computer and use it in GitHub Desktop.
Save switz/4084014 to your computer and use it in GitHub Desktop.
Client side and Server side request wrapper (used with DerbyJS)
# src/api/phishnet.coffee
API_KEY = 'removed'
API_URL = 'api.phish.net/api.js'
METHOD = 'pnet.shows.setlists.get'
API_FORMAT = 'json'
API_VERSION = '2.0'
Request = require '../lib/request'
{ toParam, onClient } = require '../lib/utils'
phishNetRequestUrl = (showDate) ->
params =
method : METHOD
apikey : API_KEY
showdate : showDate
api : API_VERSION
format : API_FORMAT
"http://#{ API_URL }?#{ toParam(params) }"
clientSideJSONRequest = (requestUrl, callback) ->
requestUrl += '&callback=?'
# jQuery
$.getJSON requestUrl, (data) ->
callback data[0]
# ### PhishAPI.get(showDate, callback)
# `params`: (string) formatted show date
#
# `callback`: (function)
#
get = (showDate, callback) ->
requestUrl = phishNetRequestUrl(showDate)
if onClient()
clientSideJSONRequest(requestUrl, callback)
else
request = new Request(requestUrl)
request.done (response) ->
callback JSON.parse(response)[0]
request.fire()
module.exports = { get }
# src/lib/request.coffee
http = require 'http'
# ### Request
#
# The Request class is just a wrapper
# around the `http.request` function,
# providing a cleaner and more reusable
# interface.
#
# `constructor(options)`
#
# `options` can be anything `http.request` takes.
#
# Callbacks can be queued up by calling `request.done`
# and passing it a callback function to be invoked when the
# http request has completed
#
# Example:
#
# callback = (json) ->
# doSomethingWithJSON( json )
#
# request = new Request('http://api.phish.net/api.js?')
# request.done (response) ->
# callback JSON.parse(response)[0]
#
# request.fire(data) # data refers to the post data
#
class Request
constructor: (@options) ->
@callbacks = {}
fire: (data) ->
request = http.request(@options, @_handler)
request.on 'error', (err) =>
for callback in @callbacks['fail']
callback(err)
# Send data with request
if data
request.write data
request.end()
this
done: (callback) ->
push.call(this, 'done', callback)
this
fail: (callback) ->
push.call(this, 'fail', callback)
this
###########
# PRIVATE #
###########
_handler: (response) =>
data = ''
response.on 'data', (chunk) ->
data += chunk
response.on 'end', =>
for callback in @callbacks['done']
callback(data)
push = (type, callback) ->
@callbacks[type] ?= []
@callbacks[type].push callback
module.exports = Request
# src/lib/utils.coffee
derby = require 'derby'
onServer = ->
derby.util.isServer
onClient = ->
!onServer()
toParam = (object) ->
params = []
for own key, val of object
params.push("#{ key }=#{ val }")
params.join('&')
module.exports =
{
onServer
onClient
toParam
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment