Edits history of script submission #24015 for ' Invoke Lambda function (aws_lambda)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda"
    
    /**
     * Invoke Lambda function
     * Invoke a Lambda function with a JSON payload (object or array), synchronously (RequestResponse) or asynchronously (Event). Returns the status code, the function error if the function failed, the parsed response payload and the decoded log tail (synchronous calls only). A function error is returned with status 200, not thrown. Needs lambda:InvokeFunction.
     */
    export async function main(
      auth: RT.Aws,
      function_name: string,
      payload: object | undefined,
      invocation_type: "RequestResponse" | "Event" | undefined,
      qualifier: string | undefined,
      include_log_tail: boolean = true
    ) {
      const client = new LambdaClient({
        region: auth.region || undefined,
        credentials: {
          accessKeyId: auth.awsAccessKeyId,
          secretAccessKey: auth.awsSecretAccessKey,
        },
      })
    
      const type = invocation_type || "RequestResponse"
      const response = await client.send(
        new InvokeCommand({
          FunctionName: function_name,
          InvocationType: type,
          Qualifier: qualifier || undefined,
          // LogType Tail only applies to synchronous invocations
          LogType:
            type === "RequestResponse" && include_log_tail !== false
              ? "Tail"
              : undefined,
          Payload:
            payload != null
              ? new TextEncoder().encode(JSON.stringify(payload))
              : undefined,
        })
      )
    
      const text = response.Payload
        ? new TextDecoder().decode(response.Payload)
        : ""
      let parsed: unknown = null
      if (text !== "") {
        try {
          parsed = JSON.parse(text)
        } catch {
          parsed = text
        }
      }
    
      return {
        status_code: response.StatusCode,
        function_error: response.FunctionError ?? null,
        executed_version: response.ExecutedVersion ?? null,
        payload: parsed,
        log_tail: response.LogResult
          ? Buffer.from(response.LogResult, "base64").toString("utf8")
          : null,
      }
    }
    

    Submitted by hugo989 2 hours ago