For this, I have created a serverless application using Nodejs 16.x.
To connect to SQL database from lambda, I am using Nuget package ‘mssql’.
In your serverless application, install mssql like below –
npm install mssql
Usage –
I am using Typescript and DBConfig used above is just an interface.
Also replace all the config with your database credentials.
import sql from "mssql";
const config : DBConfig = {
user: ${process.env.DB_USER},
password: ${process.env.DB_PASSWORD},
server: ${process.env.DB_SERVER},
database: ${process.env.DATABASE},
options: {
trustServerCertificate: true,
},
};
export const run = async () => {
try {
await sql.connect(config);
const result = await sql.query`Select * from [TableName]`;
var result = result.recordset;
}
catch (err) {
console.error("Error:", err);
return {
statusCode: 500,
body: JSON.stringify({
message: "Error accessing the database.",
error: err,
}),
};
}
}
Please note that the RDS and lambda should be in same VPC settings. If while running lambda, you get a timeout error, do verify the VPC settings for both RDS and lambda. If they are in different VPC, then you have to do further settings. Please refer to AWS documentation for that.
Also make sure the IAM role in lambda should have permission to access RDS
Refer to this if you are looking to send an email with attachment from lambda.