|
| 1 | +import { DataSourcePlugin } from "openblocks-sdk/dataSource"; |
| 2 | +import dataSourceConfig, { DataSourceDataType } from "./dataSourceConfig"; |
| 3 | +import queryConfig, { ActionDataType } from "./queryConfig"; |
| 4 | +import { |
| 5 | + LambdaClient, |
| 6 | + ListFunctionsCommand, |
| 7 | + InvokeCommand, |
| 8 | + InvocationType, |
| 9 | +} from "@aws-sdk/client-lambda"; |
| 10 | +import _ from "lodash"; |
| 11 | +import { safeJsonParse } from "../../common/util"; |
| 12 | + |
| 13 | +function getClient(dataSourceConfig: DataSourceDataType) { |
| 14 | + const { accessKey, secretKey, region } = dataSourceConfig; |
| 15 | + const client = new LambdaClient({ |
| 16 | + credentials: { |
| 17 | + accessKeyId: accessKey, |
| 18 | + secretAccessKey: secretKey, |
| 19 | + }, |
| 20 | + region, |
| 21 | + }); |
| 22 | + return client; |
| 23 | +} |
| 24 | + |
| 25 | +const lambdaPlugin: DataSourcePlugin<ActionDataType, DataSourceDataType> = { |
| 26 | + id: "lambda", |
| 27 | + name: "Lambda", |
| 28 | + category: "api", |
| 29 | + icon: "lambda.svg", |
| 30 | + dataSourceConfig, |
| 31 | + queryConfig, |
| 32 | + validateDataSourceConfig: async function (dataSourceConfig) { |
| 33 | + const client = getClient(dataSourceConfig); |
| 34 | + const ret = await client.send(new ListFunctionsCommand({ MaxItems: 1 })); |
| 35 | + return { |
| 36 | + success: Array.isArray(ret.Functions), |
| 37 | + }; |
| 38 | + }, |
| 39 | + run: async function (actionData, dataSourceConfig): Promise<any> { |
| 40 | + const client = getClient(dataSourceConfig); |
| 41 | + if (actionData.actionName === "ListFunctions") { |
| 42 | + const ret = await client.send( |
| 43 | + new ListFunctionsCommand({ |
| 44 | + Marker: actionData.marker || undefined, |
| 45 | + MaxItems: actionData.limit, |
| 46 | + }) |
| 47 | + ); |
| 48 | + return { |
| 49 | + functions: ret.Functions?.map((i) => i.FunctionName) || [], |
| 50 | + nextMarker: ret.NextMarker || "", |
| 51 | + }; |
| 52 | + } |
| 53 | + |
| 54 | + if (actionData.actionName === "InvokeFunction") { |
| 55 | + const ret = await client.send( |
| 56 | + new InvokeCommand({ |
| 57 | + FunctionName: actionData.functionName, |
| 58 | + InvocationType: actionData.invocationType, |
| 59 | + Payload: Uint8Array.from( |
| 60 | + JSON.stringify(actionData.payload || {}) |
| 61 | + .split("") |
| 62 | + .map((i) => i.charCodeAt(0)) |
| 63 | + ), |
| 64 | + }) |
| 65 | + ); |
| 66 | + if (actionData.invocationType === InvocationType.RequestResponse) { |
| 67 | + return (ret.Payload && safeJsonParse(Buffer.from(ret.Payload).toString("utf-8"))) || {}; |
| 68 | + } |
| 69 | + return { |
| 70 | + statusCode: ret.StatusCode, |
| 71 | + }; |
| 72 | + } |
| 73 | + }, |
| 74 | +}; |
| 75 | + |
| 76 | +export default lambdaPlugin; |
0 commit comments