= Cheatsheet Node.js =
**Summary**: Nodejs hints, tips, oneliners and best practices. \\
**Date**: 8 December 2024 \\
{{tag>cheatsheet nodejs}}
= AWS Lambda Node.js =
== Get Dynamo DB Table as Log ==
const AWS = require("aws-sdk");
const dynamodb = new AWS.DynamoDB();
// Get Time in the Netherlands
var dutchTime = new Date().toLocaleString('en-US', {timeZone: "Europe/Amsterdam"});
var requestTime = new Date(dutchTime);
var year = requestTime.getFullYear();
var month = requestTime.getMonth() + 1; //Months go from 0 - 11
// Set months to get logs for
if (month === 1){
var fullMonth = year + "-0" + month;
var lastMonth = (year - 1 ) + "-12";
}
if (month > 1 && month < 10){
var fullMonth = year + "-0" + month;
var lastMonth = year + "-0" + (month - 1);
}
if (month === 10){
var fullMonth = year + "-" + month;
var lastMonth = year + "-0" + (month - 1);
}
if (month > 10){
var fullMonth = year + "-" + month;
var lastMonth = year + "-" + (month - 1);
}
const params = {
TableName: 'LogTable',
FilterExpression: 'begins_with(RequestTime, :RequestTime) OR begins_with(RequestTime, :RequestTime2)',
ExpressionAttributeValues: {
':RequestTime': {S: fullMonth},
':RequestTime2': {S: lastMonth},
},
};
exports.handler = (event, context, callback) => {
console.log(fullMonth + lastMonth);
dynamodb.scan(params, (err, data) => {
if(err){
console.log('Error on retrieving log data ' + err);
}
callback(null, data['Items']);
});
};
== Send Email ==
//jshint esversion:6
/* IAM-Access
Description: Sends the end email to the customer with all required information.
Links:
- AWS Javascript SDK for SES: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html
- Util.inspect and JSON.stringify: https://medium.com/@reginald.johnson/testing-aws-lambda-functions-the-easy-way-41cf1ed8c090
*/
// AWS Variables
var aws = require('aws-sdk');
aws.config.update({region: 'eu-west-1'});
// SES const & vars
const ses = new aws.SES();
var util = require('util');
var emailfrom = 'info@shiftwiki . nl';
// Workflow Variables
// Declaring the customerData variable
var customerData;
// Send email to customer
function sendMail(params){
console.log("Start function sendMail. Email address: " + params.email );
if (customerData.discountCode === "testmodus"){
emailto = 'sjoerd@shiftwiki .nl';
emailfrom = 'info@shiftwiki .nl';
} else {
emailto = params.email;
}
console.log("Email address: " + emailto );
//email
var mailparams = {
Destination: {
ToAddresses: [emailto]
},
Message: {
Body: {
Html: {
Charset: "UTF-8",
Data: "Dear " + params.firstname + " " + params.lastname +
"
" +
"All is ready. " +
"
" +
"Kind regards,
" +
"Shift"
}
},
Subject: { Data: "[SHIFT]Ready. "}
},
Source: emailfrom
};
return ses.sendEmail(mailparams).promise();
}
// Error Handling
function errorResponse(message) {
this.name = "email-to-customer-end";
this.message = message;
}
errorResponse.prototype = new Error();
exports.handler = (event, context, callback) => {
console.log("Start email-to-customer-end");
//console.log(event);
//console.log(context);
customerData = event;
// Display available information
console.log(customerData);
// Invoke function sendmail
sendMail(customerData).then(() => {
customerData.status = customerData.status + "Customer end email sent out. ";
callback(null, customerData);
}).catch((err) => {
// Error to CloudWatch
console.error(err);
// Add Error to Task Output
const error = new errorResponse(err.message);
callback(error);
});
};
== Create S3 Bucket ==
//jshint esversion:6
/* S3-Buckets-Add
Description: Creates two S3 buckets, configure access policy, website hosting and redirect.
Original PowerShell Script:
### S3 Bucket Creation as a Static Website ###
New-S3Bucket -BucketName $bucketname -PublicReadOnly
Write-S3BucketWebsite -BucketName $bucketname -WebsiteConfiguration_IndexDocumentSuffix index.html -WebsiteConfiguration_ErrorDocument error.html
$s3policy = '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::bucketnameplaceholder/*"}]}'
$s3policy = $s3policy -replace "bucketnameplaceholder", "$bucketname"
Write-S3BucketPolicy -BucketName "$bucketname" -Policy $s3policy
write-host "S3 Bucket $bucketname was created on $((Get-S3Bucket -BucketName $bucketname).creationdate) "
### S3 Bucket Creation Redirect ###
New-S3Bucket -BucketName $wwwbucketname
Add-S3PublicAccessBlock -BucketName $wwwbucketname `
-PublicAccessBlockConfiguration_BlockPublicAcl $true `
-PublicAccessBlockConfiguration_BlockPublicPolicy $true `
-PublicAccessBlockConfiguration_IgnorePublicAcl $true `
-PublicAccessBlockConfiguration_RestrictPublicBucket $true
Write-S3BucketWebsite -BucketName $wwwbucketname -RedirectAllRequestsTo_HostName $bucketname
write-host "S3 Bucket $wwwbucketname was created on $((Get-S3Bucket -BucketName $wwwbucketname).creationdate) "
Links:
- AWS Javascript SDK for S3: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html
*/
// AWS Variables
var aws = require('aws-sdk');
aws.config.update({region: 'eu-west-1'});
var s3 = new aws.S3();
// Workflow Variables
// Declaring the customerData variable
var customerData;
//function s3BucketCreate
function s3BucketCreate(params) {
console.log("Start function s3BucketCreate. Input: " + params.domainname);
return s3.createBucket({
Bucket: params.domainname,
CreateBucketConfiguration: {
LocationConstraint: aws.config.region
},
ACL: "public-read"
}).promise();
}
//function s3wwwBucketCreate
function s3wwwBucketCreate(params) {
console.log("Start function s3wwwBucketCreate. Input: " + params.wwwdomainname);
return s3.createBucket({
Bucket: params.wwwdomainname,
CreateBucketConfiguration: {
LocationConstraint: aws.config.region
}
}).promise();
}
//function s3BucketWebsite
function s3BucketWebsite(params){
console.log("Start function s3BucketWebsite. Input: " + params.domainname);
return s3.putBucketWebsite({
Bucket: params.domainname,
WebsiteConfiguration: {
ErrorDocument: {
Key: 'error.html'
},
IndexDocument: {
Suffix: 'index.html'
}
}
}).promise();
}
//function s3BucketPolicy
function s3BucketPolicy(params){
console.log("Start function s3BucketPolicy. Input: " + params.domainname);
var s3policyplaceholder = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::domainnameplaceholder/*\"}]}";
var s3policy = s3policyplaceholder.replace("domainnameplaceholder", params.domainname);
return s3.putBucketPolicy({
Bucket: params.domainname,
Policy: s3policy,
}).promise();
}
//function s3BucketPublicAccessBlock
function s3BucketPublicAccessBlock(params){
console.log("Start function s3BucketPublicAccessBlock. Input: " + params.wwwdomainname);
return s3.putPublicAccessBlock({
Bucket: params.wwwdomainname,
PublicAccessBlockConfiguration: {
BlockPublicAcls: true,
BlockPublicPolicy: true,
IgnorePublicAcls: true,
RestrictPublicBuckets: true
}
}).promise();
}
//function s3BucketWebsiteRedirect
function s3BucketWebsiteRedirect(params){
console.log("Start function s3BucketWebsiteRedirect. Input: " + params.wwwdomainname + " and " + params.domainname);
return s3.putBucketWebsite({
Bucket: params.wwwdomainname,
WebsiteConfiguration: {
RedirectAllRequestsTo: {
HostName: params.domainname
}
}
}).promise();
}
// Error Handling
function errorResponse(message) {
this.name = "s3-buckets-add";
this.message = message;
}
errorResponse.prototype = new Error();
exports.handler = (event, context, callback) => {
console.log("Start s3-buckets-add");
// console.log(event);
customerData = event;
// Display available information
console.log(customerData);
// create params variable to pass to s3 functions
var params = {
domainname: customerData.domainname,
wwwdomainname: customerData.wwwdomainname
};
// Invoke function s3BucketCreate
s3BucketCreate(params).then(() => {
customerData.status = customerData.status + "S3 Bucket creation success. ";
s3BucketWebsite(params).then(() => {
customerData.status = customerData.status + "S3 Bucket configured as website. ";
s3BucketPolicy(params).then(() => {
customerData.status = customerData.status + "S3 Bucket Policy set. ";
s3wwwBucketCreate(params).then(() => {
customerData.status = customerData.status + "S3 wwwBucket creation success. ";
s3BucketPublicAccessBlock(params).then(() => {
customerData.status = customerData.status + "S3 wwwBucket public access blocked. ";
s3BucketWebsiteRedirect(params).then(() => {
customerData.status = customerData.status + "S3 wwwBucket redirected to S3 Bucket. ";
callback(null, customerData);
}).catch((err) => {
// Error to CloudWatch
console.error(err);
// Add Error to Task Output
const error = new errorResponse(err.message);
callback(error);
});
}).catch((err) => {
// Error to CloudWatch
console.error(err);
// Add Error to Task Output
const error = new errorResponse(err.message);
callback(error);
});
}).catch((err) => {
// Error to CloudWatch
console.error(err);
// Add Error to Task Output
const error = new errorResponse(err.message);
callback(error);
});
}).catch((err) => {
// Error to CloudWatch
console.error(err);
// Add Error to Task Output
const error = new errorResponse(err.message);
callback(error);
});
}).catch((err) => {
// Error to CloudWatch
console.error(err);
// Add Error to Task Output
const error = new errorResponse(err.message);
callback(error);
});
}).catch((err) => {
// Error to CloudWatch
console.error(err);
// Add Error to Task Output
const error = new errorResponse(err.message);
callback(error);
});
};