miniature-arm-21874
04/10/2020, 6:30 PMconst lambda = async (event, context) => {
const knex = Knex(...);
knex.query(...)
}
this establishes a connection inside of the function invocation and as a result
can't be used between separate invocations with lambda's container use but also
takes time to start up each time as a result.
The best practices suggest initialising sdks and connections outside of the handler
https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html
is it possible to create lambdas a bit like in the below example?
const knex = Knex(...);
const lambda = async (event, context) => {
knex.query(...)
}
tall-librarian-49374
04/10/2020, 6:48 PMminiature-arm-21874
04/10/2020, 8:40 PMacceptable-stone-35112
04/14/2020, 1:46 PMminiature-arm-21874
04/14/2020, 2:08 PMimport { Callback, Context } from '@pulumi/aws/lambda';
import { BucketEvent } from '@pulumi/aws/s3';
import * as Knex from 'knex';
const conversationsToPostgresFactory = (): Callback<BucketEvent, void> => {
const knex = Knex({
client: 'pg',
connection: {
host: process.env.DB_HOST,
user: process.env.DB_USER,
port: Number(process.env.DB_PORT),
password: process.env.DB_PASS,
database: process.env.DB_NAME,
},
useNullAsDefault: true,
});
return async function conversationsToPostgres(
event: BucketEvent,
context: Context
): Promise<void> {
context.callbackWaitsForEmptyEventLoop = false;
const records = [{}];
return await knex.transaction(async (transaction) => {
await transaction('conversations').insert(records);
});
};
};
const sendToPostgresLambda = new aws.lambda.CallbackFunction(
'conversation-data-to-postgres',
{
timeout: 150,
memorySize: 256,
callbackFactory: conversationsToPostgres,
runtime: aws.lambda.NodeJS12dXRuntime,
environment: {
variables: {
DB_HOST: rds.address,
DB_USER: rds.username,
DB_PASS: password.result,
DB_PORT: rds.port.apply((port) => port.toString()),
DB_NAME: rds.name,
},
},
vpcConfig: {
securityGroupIds: rds.vpcSecurityGroupIds,
subnetIds: vpc.publicSubnetIds,
},
deadLetterConfig: {
targetArn: sendToPostgresDLQueue.arn,
},
}
);
acceptable-stone-35112
04/15/2020, 7:46 AMminiature-arm-21874
04/15/2020, 8:31 AMconversationsToPostgresFactory
becomes the lambda function code, and the handler is a function within that