amazonica icon indicating copy to clipboard operation
amazonica copied to clipboard

Update README.md Lambda Section

Open mustangJaro opened this issue 4 years ago • 0 comments

Reference Location: https://github.com/mcohen01/amazonica#lambda

I had a difficult time parsing the response from invoking a Lambda call, so I think it'd be helpful to include instructions for how to do that here.

Existing

(ns com.example
  (:use [amazonica.aws.lambda]))

(let [role "arn:aws:iam::123456789012:role/some-lambda-role"
      handler "exports.helloWorld = function(event, context) {
                  console.log('value1 = ' + event.key1)
                  console.log('value2 = ' + event.key2)
                  console.log('value3 = ' + event.key3)
                  context.done(null, 'Hello World')
                }"]
  (create-function :role role :function handler))

(invoke :function-name "helloWorld"
        :payload "{\"key1\": 1, \"key2\": 2, \"key3\": 3}")

Proposed

(ns com.example
  (:use [amazonica.aws.lambda])
  (:require 
   [cheshire.core :as json]
   [clojure.walk :as walk])
  (:import (java.util Base64)))

(defn byte-array->string [byte-array]
  (.encodeToString (Base64/getEncoder) byte-array))

(defn decode-byte-buffer [payload]
  (->> payload
       (.decode (Base64/getDecoder))
       (String.)
       (json/parse-string)
       (walk/keywordize-keys)))

(defn parse-payload [invoke-result]
  (->> (:payload invoke-result)
       (.array)
       (byte-array->string)
       (decode-byte-buffer)))

(let [role "arn:aws:iam::123456789012:role/some-lambda-role"
      handler "exports.helloWorld = function(event, context) {
                  console.log('value1 = ' + event.key1)
                  console.log('value2 = ' + event.key2)
                  console.log('value3 = ' + event.key3)
                  context.done(null, 'Hello World')
                }"]
  (create-function :role role :function handler))

(let [invoke-result (invoke :function-name "helloWorld"
                            :payload "{\"key1\": 1, \"key2\": 2, \"key3\": 3}")]
  (parse-payload invoke-result))

mustangJaro avatar Nov 10 '20 19:11 mustangJaro