aws-sdk#Lambda TypeScript Examples

The following examples show how to use aws-sdk#Lambda. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From malagu with MIT License 7 votes vote down vote up
export async function getAlias(client: Lambda, functionName: string, aliasName: string, print = false) {

    try {
        const result = await client.getAlias({ FunctionName: functionName, Name: aliasName }).promise();
        if (print) {
            console.log(chalk`{bold.cyan - Alias:}`);
            console.log(`    - AliasName: ${result.Name}`);
            console.log(`    - FunctionVersion: ${result.FunctionVersion}`);
        }
        return result
    } catch (error) {
        if (error.statusCode !== 404) {
            throw error;
        }
    }

}
Example #2
Source File: utils.ts    From malagu with MIT License 7 votes vote down vote up
export async function createClients(region: string, credentials: Credentials) {
    const clientConfig = {
        region,
        credentials: {
            accessKeyId: credentials.accessKeyId,
            secretAccessKey: credentials.accessKeySecret,
            sessionToken: credentials.token
        }
    };
    return {
        lambdaClient: new Lambda(clientConfig),
        apiGatewayClient: new ApiGatewayV2(clientConfig),
        iamClient: new IAM(clientConfig)
    }
}
Example #3
Source File: utils.ts    From malagu with MIT License 7 votes vote down vote up
export async function getTrigger(client: Lambda, functionName: string, eventSourceArn?: string, aliasName?: string, print = false) {
    const listEventSourceMappingsRequest: Lambda.Types.ListEventSourceMappingsRequest = {
        FunctionName: functionName,
        MaxItems: 100
    };
    const resp = await client.listEventSourceMappings(listEventSourceMappingsRequest).promise();
    const result = resp
        .EventSourceMappings?.find(e => eventSourceArn && e.EventSourceArn === eventSourceArn || aliasName && e.FunctionArn?.endsWith(`:${functionName}:${aliasName}`));
    if (result) {
        if (print) {
            console.log(chalk`\n{bold.cyan - Trigger:}`);
            console.log(`    - EventSourceArn: ${result.EventSourceArn}`);
            console.log(`    - State: ${result.State}`);
            console.log(`    - LastModified: ${result.LastModified}`);
        }
        return result;
    }
    
}
Example #4
Source File: sdk-calls.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
getLambdaFunction = async (functionName, region) => {
  const lambda = new Lambda();
  let res;
  try {
    res = await lambda.getFunction({ FunctionName: functionName }).promise();
  } catch (e) {
    console.log(e);
  }
  return res;
}
Example #5
Source File: lambda-function.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
functionCloudInvoke = async (
  cwd: string,
  settings: { funcName: string; payload: string },
): Promise<Lambda.InvocationResponse> => {
  const meta = getProjectMeta(cwd);
  const lookupName = settings.funcName;
  expect(meta.function[lookupName]).toBeDefined();
  const { Name: functionName, Region: region } = meta.function[lookupName].output;
  expect(functionName).toBeDefined();
  expect(region).toBeDefined();
  const result = await invokeFunction(functionName, settings.payload, region);
  if (!result.$response.data) {
    fail('No data in lambda response');
  }
  return result.$response.data as Lambda.InvocationResponse;
}
Example #6
Source File: lambda-client.ts    From crossfeed with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
/**
   * Invokes a lambda function with the given name.
   */
  async runCommand({
    name
  }: {
    name: string;
  }): Promise<Lambda.InvocationResponse> {
    console.log('Invoking lambda function ', name);
    if (this.isLocal) {
      scheduler({}, {} as any, () => null);
      return { StatusCode: 202, Payload: '' };
    } else {
      // Invoke lambda asynchronously
      return this.lambda
        .invoke({
          FunctionName: name,
          InvocationType: 'Event',
          Payload: ''
        })
        .promise();
    }
  }
Example #7
Source File: utils.ts    From malagu with MIT License 6 votes vote down vote up
export async function getFunction(client: Lambda, functionName: string, qualifier?: string, print = false) {

    try {
        const result = await client.getFunction({ FunctionName: functionName, Qualifier: qualifier }).promise();
        if (print && result.Configuration) {
            const functionInfo = result.Configuration;
            console.log(chalk`{bold.cyan - Function:}`);
            console.log(`    - FunctionName: ${functionName}`);
            console.log(`    - State: ${functionInfo.State}`);
            console.log(`    - StateReason: ${functionInfo.StateReason}`);
            console.log(`    - LastUpdateStatus: ${functionInfo.LastUpdateStatus}`);
            console.log(`    - Timeout: ${functionInfo.LastUpdateStatusReason}`);
            console.log(`    - FunctionArn: ${functionInfo.FunctionArn}`);
            console.log(`    - KMSKeyArn: ${functionInfo.KMSKeyArn}`);
            console.log(`    - MemorySize: ${functionInfo.MemorySize}`);
            console.log(`    - Role: ${functionInfo.Role}`);
            console.log(`    - Runtime: ${functionInfo.Runtime}`);
            console.log(`    - LastModifiedTime: ${functionInfo.LastModified}`);

            const vpcConfig = functionInfo.VpcConfig;
            if (vpcConfig?.VpcId) {
                console.log('    - VpcConfig:');
                console.log(`        - VpcId: ${vpcConfig.VpcId}`);
                console.log(`        - SubnetIds: ${vpcConfig.SubnetIds}`);
                console.log(`        - SubnetIds: ${vpcConfig.SecurityGroupIds}`);
            }

            const deadLetterConfig = functionInfo.DeadLetterConfig;
            if (deadLetterConfig?.TargetArn) {
                console.log('    - DeadLetterConfig:');
                console.log(`        - TargetArn: ${deadLetterConfig.TargetArn}`);
            }

            const fileSystemConfigs = functionInfo.FileSystemConfigs;
            if (fileSystemConfigs?.length) {
                console.log('    - FileSystemConfig:');
                for (const config of fileSystemConfigs) {
                    console.log(`        - Arn: ${config.Arn}`);
                    console.log(`          LocalMountPath: ${config.LocalMountPath}`);
                }
            }

            const tracingConfig = functionInfo.TracingConfig;
            if (tracingConfig?.Mode) {
                console.log('    - TracingConfig:');
                console.log(`        - Mode: ${tracingConfig.Mode}`);
            }
        }
        return result;
        
    } catch (error) {
        if (error.statusCode !== 404) {
            throw error;
        }
    }

}
Example #8
Source File: deploy.ts    From malagu with MIT License 6 votes vote down vote up
async function createTrigger(trigger: any, functionName: string) {

    const oldEventSourceMapping = await getTrigger(lambdaClient, functionName, trigger.eventSourceArn);
    if (oldEventSourceMapping) {
        const deleteEventSourceMappingRequest: Lambda.Types.DeleteEventSourceMappingRequest = {
            UUID: oldEventSourceMapping.UUID!
        };
        await lambdaClient.deleteEventSourceMapping(deleteEventSourceMappingRequest).promise();

    }
    const createEventSourceMappingRequest: Lambda.Types.CreateEventSourceMappingRequest = camelcaseKeys(trigger, { pascalCase: true });

    await SpinnerUtil.start(`Set a ${trigger.name} Trigger`, async () => {
        await lambdaClient.createEventSourceMapping(createEventSourceMappingRequest).promise();
    });
}
Example #9
Source File: deploy.ts    From malagu with MIT License 6 votes vote down vote up
async function parseCreateFunctionRequest(functionMeta: any) {
    const config = parseUpdateFunctionConfigurationRequest(functionMeta);
    delete config.RevisionId;

    const req: Lambda.Types.CreateFunctionRequest = {
        ...config,
        Role: functionMeta.role,
        CodeSigningConfigArn: functionMeta.codeSigningConfigArn,
        PackageType: functionMeta.packageType,
        Publish: functionMeta.publish,
        Tags: functionMeta.tags,
        Code: await parseFunctionCode(functionMeta)
    };
    return req;
}
Example #10
Source File: deploy.ts    From malagu with MIT License 6 votes vote down vote up
function parseUpdateAliasRequest(aliasMeta: any, functionName: string, functionVersion: string) {
    const req: Lambda.Types.UpdateAliasRequest = {
        Name: aliasMeta.name,
        FunctionName: functionName,
        Description: aliasMeta.description,
        FunctionVersion: functionVersion
    };

    const { routingConfig } = aliasMeta;
    if (routingConfig) {
        req.RoutingConfig = {
            AdditionalVersionWeights: routingConfig.additionalVersionWeights
        };
    }
    return req;
}
Example #11
Source File: lambda-client.ts    From crossfeed with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
lambda: Lambda;
Example #12
Source File: lambda-client.ts    From crossfeed with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
constructor() {
    this.isLocal =
      process.env.IS_OFFLINE || process.env.IS_LOCAL ? true : false;
    if (!this.isLocal) {
      this.lambda = new Lambda();
    }
  }
Example #13
Source File: info.ts    From malagu with MIT License 5 votes vote down vote up
lambdaClient: Lambda
Example #14
Source File: deploy.ts    From malagu with MIT License 5 votes vote down vote up
lambdaClient: Lambda
Example #15
Source File: deploy.ts    From malagu with MIT License 5 votes vote down vote up
function parseCreateAliasRequest(aliasMeta: any, functionName: string, functionVersion: string) {
    const req: Lambda.Types.CreateAliasRequest = <Lambda.Types.CreateAliasRequest>{
        ...parseUpdateAliasRequest(aliasMeta, functionName, functionVersion)
    };
    return req;
}
Example #16
Source File: deploy.ts    From malagu with MIT License 5 votes vote down vote up
async function createOrUpdateFunction(functionMeta: any, accountId: string, region: string, disableProjectId: boolean) {
    projectId = await ProjectUtil.getProjectId();
    let functionInfo: any;
    if (disableProjectId) {
        functionInfo = await getFunction(lambdaClient, functionMeta.name);
    } else {
        if (!projectId) {
            await tryCreateProjectId(functionMeta.name);
            await ProjectUtil.saveProjectId(projectId);
            functionMeta.name = `${functionMeta.name}_${projectId}`;
        } else {
            functionMeta.name = `${functionMeta.name}_${projectId}`;
            functionInfo = await getFunction(lambdaClient, functionMeta.name);
        }
    }

    await createRoleIfNeed(functionMeta, accountId, region);

    if (functionInfo) {
        await SpinnerUtil.start(`Update ${functionMeta.name} function${functionMeta.sync === 'onlyUpdateCode' ? ' (only update code)' : ''}`, async () => {
            const updateFunctionCodeRequest: Lambda.Types.UpdateFunctionCodeRequest = {
                FunctionName: functionMeta.name,
                ...await parseFunctionCode(functionMeta)
            };
            await lambdaClient.updateFunctionCode(updateFunctionCodeRequest).promise();

            await checkStatus(functionMeta.name);

            if (functionMeta.sync !== 'onlyUpdateCode') {
                let updateConfig = parseUpdateFunctionConfigurationRequest(functionMeta);
                delete updateConfig.Runtime;
                
                functionInfo = await lambdaClient.updateFunctionConfiguration(updateConfig).promise();
            }
        });
    } else {
        functionInfo = await SpinnerUtil.start(`Create ${functionMeta.name} function`, async () => {
            return await createFunctionWithRetry(functionMeta);
        });
    }
}
Example #17
Source File: deploy.ts    From malagu with MIT License 5 votes vote down vote up
function parseUpdateFunctionConfigurationRequest(functionMeta: any) {

    const req: Lambda.Types.UpdateFunctionConfigurationRequest = {
        FunctionName: functionMeta.name,
        Description: functionMeta.description,
        Runtime: functionMeta.runtime,
        Timeout: functionMeta.timeout,
        Role: functionMeta.role,
        Handler: functionMeta.handler,
        KMSKeyArn: functionMeta.kmsKeyArn,
        MemorySize: functionMeta.memorySize,
        RevisionId: functionMeta.revisionId,
        Layers: functionMeta.layers
    };

    const { deadLetterConfig, environment, fileSystemConfigs, imageConfig, vpcConfig, tracingConfig, } = functionMeta;
    if (environment) {
            req.Environment = {
            Variables: environment.variables
        };
    }

    if (vpcConfig) {
        req.VpcConfig = {
            SecurityGroupIds: vpcConfig.securityGroupIds,
            SubnetIds: vpcConfig.subnetIds
        };
    }

    if (deadLetterConfig) {
        req.DeadLetterConfig = {
            TargetArn: deadLetterConfig.targetArn
        };
    }

    if (imageConfig) {
        req.ImageConfig = {
            Command: imageConfig.command,
            EntryPoint: imageConfig.entryPoint,
            WorkingDirectory: imageConfig.workingDirectory
        };
    }

    if (tracingConfig) {
        req.TracingConfig = {
            Mode: tracingConfig.mode
        };
    }

    if (fileSystemConfigs) {
        req.FileSystemConfigs = [];
        for (const fileSystemConfig of fileSystemConfigs) {
            req.FileSystemConfigs.push({
                Arn: fileSystemConfig.arn,
                LocalMountPath: fileSystemConfig.localMountPath
            });
        }
    }
    return req;
}
Example #18
Source File: sdk-calls.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
getEventSourceMappings = async (functionName: string, region: string) => {
  const service = new Lambda({ region });
  return (await service.listEventSourceMappings({ FunctionName: functionName }).promise()).EventSourceMappings;
}
Example #19
Source File: sdk-calls.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
invokeFunction = async (functionName: string, payload: string, region: string) => {
  const service = new Lambda({ region });
  return await service.invoke({ FunctionName: functionName, Payload: payload }).promise();
}
Example #20
Source File: sdk-calls.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
listVersions = async (layerName: string, region: string) => {
  const service = new Lambda({ region });
  return await service.listLayerVersions({ LayerName: layerName }).promise();
}
Example #21
Source File: sdk-calls.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
getLayerVersion = async (functionArn: string, region: string) => {
  const service = new Lambda({ region });
  return await service.getLayerVersionByArn({ Arn: functionArn }).promise();
}
Example #22
Source File: sdk-calls.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
getFunction = async (functionName: string, region: string) => {
  const service = new Lambda({ region });
  return await service.getFunction({ FunctionName: functionName }).promise();
}