UNPKG

726 Btext/coffeescriptView Raw
1http = require 'http'
2
3port = 0
4exports.usePort = (newport) -> port = newport
5
6exports.METHODS = ['GET', 'POST', 'DELETE', 'PUT', 'HEAD']
7for method in exports.METHODS
8 do (method) ->
9 exports[method] = (path, opts={}, cb) ->
10 if not cb then cb = opts
11 accept='application/json'
12 req = {method, host: 'localhost', port, path, headers: {accept}}
13 req.headers[k] = v for k, v of opts.headers if opts.headers
14 rawBody = ""
15 req = http.request req, (res) ->
16 res.on 'data', (chnk) -> rawBody += chnk
17 res.on 'end', ->
18 cb res, JSON.parse(rawBody or null)
19 if body = opts.body
20 if 'string' != typeof body
21 body = JSON.stringify body
22 req.end body