1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | url = require 'url'
|
13 | querystring = require 'querystring'
|
14 |
|
15 | {Batman} = require './batman'
|
16 |
|
17 | Batman.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 |
|
24 | Batman.Request::send = (data) ->
|
25 | @fire 'loading'
|
26 | requestURL = url.parse(@get 'url', true)
|
27 | protocol = requestURL.protocol
|
28 |
|
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 |
|
36 | options =
|
37 | path: path
|
38 | method: @get 'method'
|
39 | port: requestURL.port
|
40 | host: requestURL.hostname
|
41 | headers: {}
|
42 |
|
43 |
|
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 |
|
58 | data = []
|
59 | response.on 'data', (d) ->
|
60 | data.push d
|
61 |
|
62 | response.on 'end', () =>
|
63 |
|
64 | data = data.join()
|
65 | @set 'response', data
|
66 |
|
67 |
|
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 |
|
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 |
|
96 | exports.Batman = Batman
|