UNPKG

2.48 kBtext/coffeescriptView Raw
1#
2# batman.node.coffee
3# batman.js
4#
5# Created by Nick Small
6# Copyright 2011, Shopify
7#
8
9# Include this file if you plan to use batman
10# with node.js.
11
12url = require 'url'
13querystring = require 'querystring'
14
15{Batman} = require './batman'
16
17Batman.Request::getModule = (protocol) ->
18 requestModule = switch protocol
19 when 'http:', 'https:'
20 require protocol.slice(0,-1)
21 else
22 throw "Unrecognized request protocol #{protocol}"
23
24Batman.Request::send = (data) ->
25 @fire 'loading'
26 requestURL = url.parse(@get 'url', true)
27 protocol = requestURL.protocol
28 # Figure out which module to use
29 requestModule = @getModule(protocol)
30 path = requestURL.pathname
31
32 if @get('method') is 'GET'
33 path += querystring.stringify Batman.mixin({}, requestURL.query, @get 'data')
34
35 # Make the request and grab the ClientRequest object
36 options =
37 path: path
38 method: @get 'method'
39 port: requestURL.port
40 host: requestURL.hostname
41 headers: {}
42
43 # Set auth if its given
44 auth = if @get 'username'
45 "#{@get 'username'}:#{@get 'password'}"
46 else if requestURL.auth
47 requestURL.auth
48
49 if auth
50 options.headers["Authorization"] = "Basic #{new Buffer(auth).toString('base64')}"
51
52 if options.method in ["PUT", "POST"]
53 options.headers["Content-type"] = @get 'contentType'
54
55 request = requestModule.request options, (response) =>
56
57 # Buffer all the chunks of data into an array
58 data = []
59 response.on 'data', (d) ->
60 data.push d
61
62 response.on 'end', () =>
63 # Join the array and set it as the response
64 data = data.join()
65 @set 'response', data
66
67 # Dispatch the appropriate event based on the status code
68 status = @set 'status', response.statusCode
69 if (status >= 200 and status < 300) or status is 304
70 @fire 'success', data
71 else
72 request.request = @
73 @fire 'error', request
74 @fire 'loaded'
75
76 # Set auth if its given
77 auth = if @get 'username'
78 "#{@get 'username'}:#{@get 'password'}"
79 else if requestURL.auth
80 requestURL.auth
81
82 if auth
83 request.setHeader("Authorization", new Buffer(auth).toString('base64'))
84
85 if @get 'method' is 'POST'
86 request.write JSON.stringify(@get 'data')
87 request.end()
88
89 request.on 'error', (e) ->
90 @set 'response', error
91 @fire 'error', error
92 @fire 'loaded'
93
94 request
95
96exports.Batman = Batman