在Coffeescript中为HTTP请求添加超时

时间:2013-10-01 04:51:57

标签: http coffeescript timeout

我需要修改一些Coffeescript以包含HTTP请求的超时。下面是代码。我试过在requestOptions字典中添加'timeout'属性,但没有运气!

以下是您也可以在Github上找到的代码(https://github.com/pcrawfor/iap_verifier/blob/master/src/iap_verifier.coffee#L144

###
  verifyReceipt

  Verifies an In App Purchase receipt string against Apple's servers

  params:
    receipt   - the receipt string
    isBase64  - Is the receipt already encoded in base64? Optional, defaults to false.
    cb        - callback function that will return the status code and results for the verification call
###
verifyReceipt: (receipt, isBase64, cb) ->
  if cb is undefined
    cb = isBase64
    isBase64 = false
  data = 
    'receipt-data': ""

  @verifyWithRetry(data, receipt, isBase64, cb)

###
  verifyWithRetry

  Verify with retry will automatically call the Apple Sandbox verification server in the event that a 21007 error code is returned.
  This error code is an indication that the app may be receiving app store review requests.    
###

verifyWithRetry: (receiptData, receipt, isBase64, cb) ->      
  encoded = null
  if isBase64
    encoded = receipt
  else
     buffer = new Buffer(receipt)
     encoded = buffer.toString('base64')

  receiptData['receipt-data'] = encoded
  @verify receiptData, @requestOptions(), (valid, msg, data) =>
    # on a 21007 error retry the request for the Sandbox environment (if the current environment is Production)
    if (21007 == data.status) && (@productionHost == @host)
      # retry...
      if @debug then console.log("Retry on Sandbox")        
      options = @requestOptions()
      options.host = @sandboxHost

      @verify receiptData, options, (valid, msg, data) ->
        if @debug then console.log("STATUS #{data.status}")
        cb(valid, msg, data)
    else
      if @debug then console.log "else"
      cb(valid, msg, data)

###
  verify the receipt data
###
verify: (data, options, cb) ->
  if @debug then console.log("verify!")

  post_data = JSON.stringify(data)

  options.headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': post_data.length
  }    

  request = https.request options, (response) =>      
    if @debug then console.log("statusCode: #{response.statusCode}")
    if @debug then console.log("headers: #{response.headers}")

    apple_response_arr = []

    response.on 'data', (data) =>
      if @debug then console.log("data #{data}")
      if response.statusCode != 200
        if @debug then console.log("error: " + data)
        return cb(false, "error", null)          

      apple_response_arr.push(data)        

    response.on 'end', () =>            
      totalData = apple_response_arr.join('')
      if @debug then console.log "end: apple response: #{totalData}"
      responseData = JSON.parse(totalData)
      @processStatus(responseData, cb)

    response.on 'timeout', () =>
      console.log('timeout')
      return cb(false, "error", null) 


  request.write(post_data)
  request.end()

  request.on 'error', (err) ->
    if @debug then console.log("In App purchase verification error: #{err}")


processStatus: (data, cb) ->
  # evaluate status code and take an action, write any new receipts to the database
  if @debug then console.log("Process status #{data.status}")
  #todo: check status code and react appropriately
  response = @responseCodes[data.status]
  # Try not to blow up if we encounter an unknown/unexepected status code
  unless response
    response =
      valid: false
      error: true
      message: "Unknown status code: " + data.status       
  cb(response.valid, response.message, data)

requestOptions: ->
  options =
    host: @host
    port: @port
    path: @path
    method: @method
#        timeout: 100  // didn't work :(

module.exports = IAPVerifier

0 个答案:

没有答案