neft
Version:
JavaScript. Everywhere.
60 lines (46 loc) • 1.79 kB
text/coffeescript
'use strict'
utils = require 'src/utils'
module.exports = (Networking) ->
requests = Object.create null
ios.httpResponseCallback = (id, error, code, resp, headers) ->
request = requests[id]
delete requests[id]
if request.type is Networking.Request.JSON_TYPE
resp = utils.tryFunction JSON.parse, null, [resp], resp
cookies = utils.tryFunction JSON.parse, null, [headers?['X-Cookies']], null
request.callback
status: code
data: resp or error
headers: headers
cookies: cookies
return
Request: require('./request.coffee') Networking
Response: require('./response.coffee') Networking
init: (networking) ->
setImmediate ->
networking.createLocalRequest
method: Networking.Request.GET
type: Networking.Request.HTML_TYPE
uri: '/'
return
###
Send a XHR request and call `callback` on response.
###
sendRequest: (req, res, callback) ->
headers = []
for name, val of req.headers
headers.push name, val
headers.push 'content-type', 'text/plain'
headers.push 'charset', 'utf-8'
headers.push 'x-expected-type', req.type
if cookies = utils.tryFunction(JSON.stringify, null, [req.cookies], null)
headers.push 'x-cookies', cookies
if typeof (data = req.data) isnt 'string'
data = utils.tryFunction JSON.stringify, null, [data], data+''
if typeof data is 'string'
headers.push 'content-length', data.length
id = ios.httpRequest req.uri, req.method, headers, data
requests[id] =
type: req.type
callback: callback
return