
var to = require('to-case')
var AWS = require('aws-sdk')

// https://stackoverflow.com/questions/39381139/how-to-stream-aws-lambda-response-in-node

module.exports = function(state, action, callback) {
  action = action.input.Action
  var lambda = new AWS.Lambda()
  var params = {
    FunctionName: to.pascal(action.type),
    Payload: JSON.stringify(action)
  }

  lambda.invoke(params, function(err, data){
    if (err) return callback(err)
    if (data.StatusCode >= 200 && data.StatusCode < 300) {
      let json = JSON.parse(data.Payload)
      if (data.errorMessage) {
        console.log(data)
        return callback(null, null)
      }
      callback(null, json)
    } else {
      console.log('data', data)
      callback(null, null)
    }
  })
}
