1 | import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda" |
2 |
|
3 | |
4 | * Invoke Lambda function |
5 | * 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. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Aws, |
9 | function_name: string, |
10 | payload: object | undefined, |
11 | invocation_type: "RequestResponse" | "Event" | undefined, |
12 | qualifier: string | undefined, |
13 | include_log_tail: boolean = true |
14 | ) { |
15 | const client = new LambdaClient({ |
16 | region: auth.region || undefined, |
17 | credentials: { |
18 | accessKeyId: auth.awsAccessKeyId, |
19 | secretAccessKey: auth.awsSecretAccessKey, |
20 | }, |
21 | }) |
22 |
|
23 | const type = invocation_type || "RequestResponse" |
24 | const response = await client.send( |
25 | new InvokeCommand({ |
26 | FunctionName: function_name, |
27 | InvocationType: type, |
28 | Qualifier: qualifier || undefined, |
29 | |
30 | LogType: |
31 | type === "RequestResponse" && include_log_tail !== false |
32 | ? "Tail" |
33 | : undefined, |
34 | Payload: |
35 | payload != null |
36 | ? new TextEncoder().encode(JSON.stringify(payload)) |
37 | : undefined, |
38 | }) |
39 | ) |
40 |
|
41 | const text = response.Payload |
42 | ? new TextDecoder().decode(response.Payload) |
43 | : "" |
44 | let parsed: unknown = null |
45 | if (text !== "") { |
46 | try { |
47 | parsed = JSON.parse(text) |
48 | } catch { |
49 | parsed = text |
50 | } |
51 | } |
52 |
|
53 | return { |
54 | status_code: response.StatusCode, |
55 | function_error: response.FunctionError ?? null, |
56 | executed_version: response.ExecutedVersion ?? null, |
57 | payload: parsed, |
58 | log_tail: response.LogResult |
59 | ? Buffer.from(response.LogResult, "base64").toString("utf8") |
60 | : null, |
61 | } |
62 | } |
63 |
|