Node.js - Amazon Web Services SDK support for TypeScript


This page details support for AWS SDK in TypeScript.

Objects

Icon Description
NodeJS Call to AWS Lambda Function
NodeJS Call to AWS Unknown Lambda Function
NodeJS AWS SNS Publisher
NodeJS AWS SQS Publisher
NodeJS AWS Kinesis Producer
NodeJS AWS Unknown SNS Publisher
NodeJS AWS Unknown SQS Publisher
NodeJS AWS Unknown Kinesis Producer
NodeJS AWS SNS Subscriber
NodeJS AWS SQS Receiver
NodeJS AWS Kinesis Consumer
NodeJS AWS Unknown SNS Subscriber
NodeJS AWS Unknown SQS Receiver
NodeJS AWS Unknown Kinesis Consumer
NodeJS Email
NodeJS SMS
NodeJS Post HttpRequest service
TypeScript Get http service
NodeJS DynamoDB Table

Lambda invocation using SDK

The SDK provides APIs to execute (i.e. invoke) lambda function. The following APIs are supported:

  • invoke method of the Lambda “aws-sdk” client of the SDK V2
  • InvokeCommand of the SDK V3

Example

When analyzing the following source code:

import * as AWS from 'aws-sdk'
// Set region

function my_invoke(){
  AWS.config.update({region: 'REGION'});
  var lambda = new AWS.Lambda();
  var params = {
    FunctionName: 'mylambda', /* required */
    //...
  };

  lambda.invoke(params, function(err, data) {
    //...
  });
}

a callLink to AWS Lambda Function object named mylambda is created. Web Services Linker links that call to lambda object to AWS Lambda Function objects having the same name:

AWS SNS

The following APIs are supported:

Library Import Supported Publisher APIs Supported Receiver APIs
AWS SDK V2 aws-sdk publish PublishCommand
AWS SDK V3 @aws-sdk/client-sns subscribe SubscribeCommand

Detailed support

A NodeJS SNS Publisher object is created whenever a publication to a topic is found by the analyzer. Its name is that of the topic. For subscriptions, a NodeJS SNS Subscriber object is created. Its name is that of the topic. Then for each supported protocol, an object is created with a callLink from the subscriber to that object. The following protocols are supported:

Protocol Object created Object name
email NodeJS Email an Email (the email addresses are not evaluated)
sms NodeJS SMS an SMS (the SMS numbers are not evaluated)
http/https NodeJS Post Service the url (evaluated from the endpoint)
sqs NodeJS AWS Simple Queue Service Publisher the name of the queue (evaluated from the endpoint)
lambda NodeJS Call to AWS Lambda Function the name of the lambda function (evaluated from the endpoint)

Example

When analyzing the following source code:

import {CreateTopicCommand, SNSClient, SubscribeCommand, PublishCommand } from "@aws-sdk/client-sns";

const REGION = "REGION"; //e.g. "us-east-1"
// Create SNS service object.
const snsClient = new SNSClient({ region: REGION });

function my_subscribe(protocol, topic_arn, endpoint){
  const params = {
    Protocol: protocol,
    TopicArn: topic_arn, //TOPIC_ARN
    Endpoint: endpoint,
  };
  const data = await snsClient.send(new SubscribeCommand(params));
};

function subcribe_to_foo_topic(){
   const topic_arn = 'arn:aws:sns:us-east-2:123456789012:foo_topic';
   my_subscribe("email", topic_arn, "EMAIL_ADDRESS")
   my_subscribe("sms", topic_arn, "007")
   my_subscribe("lambda", topic_arn, "fooarn:function:lambda_name:v2")
   my_subscribe("sqs", topic_arn, "https://sqs.us-east-2.amazonaws.com/123456789012/foo_queue")

   my_subscribe("http", topic_arn, "http://foourl")
}

function publish_to_foo_topic(){
  const params = {
      Message: "MESSAGE_TEXT", // MESSAGE_TEXT
      TopicArn: 'arn:aws:sns:us-east-2:123456789012:foo_topic'
  };
  const data = await snsClient.send(new PublishCommand(params));
}

This code will produce the following result:

AWS S3

The following links are created:

Link Type Methods from SDK V2 s3client
import {AWS} from 'aws-sdk'
const s3client = new AWS.S3()
Methods from SDK V3 s3client
import {S3} from '@aws-sdk/client-s3'
const s3client = new S3()
Commands from SDK V3
imported from @aws-sdk/client-s3
NoLink createBucket CreateBucketCommand
callLink createMultipartUpload
createPresignedPost
abortMultipartUpload
completeMultipartUpload
deleteBucketAnalyticsConfiguration
deleteBucketCors
deleteBucketEncryption
deleteBucketInventoryConfiguration
deleteBucketLifecycle
deleteBucketMetricsConfiguration
deleteBucketPolicy
deleteBucketReplication
deleteBucketTagging
deleteBucketWebsite
deleteObjectTagging
deletePublicAccessBlock
getBucketAccelerateConfiguration
getBucketAcl
getBucketAnalyticsConfiguration
getBucketCors
getBucketEncryption
getBucketInventoryConfiguration
getBucketLifecycle
getBucketLifecycleConfiguration
getBucketLocation
getBucketLogging
getBucketMetricsConfiguration
getBucketNotification
getBucketNotificationConfiguration
getBucketPolicy
getBucketPolicyStatus
getBucketReplication
getBucketTagging
getBucketVersioning
getBucketWebsite
getObjectAcl
getObjectLegalHold
getObjectLockConfiguration
getObjectRetention
getObjectTagging
getPublicAccessBlock
getSignedUrl
listBuckets
listBucketAnalyticsConfigurations
listBucketInventoryConfigurations
listBucketMetricsConfigurations
listMultipartUploads
listObjectVersions
listParts
putBucketLogging
putBucketAnalyticsConfiguration
putBucketLifecycleConfiguration
putBucketMetricsConfiguration
putBucketNotification
putBucketNotificationConfiguration
putBucketPolicy
putBucketReplication
putBucketRequestPayment
putBucketTagging
putBucketVersioning
putObjectAcl
putObjectLegalHold
putObjectLockConfiguration
putObjectRetention
putObjectTagging
putPublicAccessBlock
putBucketAccelerateConfiguration
putBucketAcl
putBucketCors
putBucketEncryption
putBucketInventoryConfiguration
putBucketLifecycle
putBucketLogging
upload
uploadPart
uploadPartCopy
abortMultipartUpload
completeMultipartUpload
copyObject
createBucket
createMultipartUpload
deleteBucket
deleteBucketAnalyticsConfiguration
deleteBucketCors
deleteBucketEncryption
deleteBucketIntelligentTieringConfiguration
deleteBucketInventoryConfiguration
deleteBucketLifecycle
deleteBucketMetricsConfiguration
deleteBucketOwnershipControls
deleteBucketPolicy
deleteBucketReplication
deleteBucketTagging
deleteBucketWebsite
deleteObjectTagging
deletePublicAccessBlock
destroy
getBucketAccelerateConfiguration
getBucketAcl
getBucketAnalyticsConfiguration
getBucketCors
getBucketEncryption
getBucketIntelligentTieringConfiguration
getBucketInventoryConfiguration
getBucketLifecycleConfiguration
getBucketLocation
getBucketLogging
getBucketMetricsConfiguration
getBucketNotificationConfiguration
getBucketOwnershipControls
getBucketPolicy
getBucketPolicyStatus
getBucketReplication
getBucketRequestPayment
getBucketTagging
getBucketVersioning
getBucketWebsite
getObjectAcl
getObjectLegalHold
getObjectLockConfiguration
getObjectRetention
getObjectTagging
getPublicAccessBlock
headBucket
headObject
listBucketAnalyticsConfigurations
listBucketIntelligentTieringConfigurations
listBucketInventoryConfigurations
listBucketMetricsConfigurations
listBuckets
listMultipartUploads
listObjectVersions
listParts
putBucketAccelerateConfiguration
putBucketAcl
putBucketCors
putBucketEncryption
putBucketIntelligentTieringConfiguration
putBucketInventoryConfiguration
putBucketLifecycleConfiguration
putBucketLogging
putBucketMetricsConfiguration
putBucketNotificationConfiguration
putBucketOwnershipControls
putBucketPolicy
putBucketReplication
putBucketRequestPayment
putBucketTagging
putBucketVersioning
putBucketWebsite
putObjectAcl
putObjectLegalHold
putObjectLockConfiguration
putObjectRetention
putObjectTagging
putPublicAccessBlock
restoreObject
send
uploadPart
uploadPartCopy
writeGetObjectResponse
AbortMultipartUploadCommand
CompleteMultipartUploadCommand
CreateMultipartUploadCommand
DeleteBucketAnalyticsConfigurationCommand
DeleteBucketCorsCommand
DeleteBucketEncryptionCommand
DeleteBucketIntelligentTieringConfigurationCommand
DeleteBucketInventoryConfigurationCommand
DeleteBucketLifecycleCommand
DeleteBucketMetricsConfigurationCommand
DeleteBucketOwnershipControlsCommand
DeleteBucketPolicyCommand
DeleteBucketReplicationCommand
DeleteBucketTaggingCommand
GetBucketAccelerateConfigurationCommand
GetBucketAclCommand
DeleteBucketWebsiteCommand
DeleteObjectTaggingCommand
DeletePublicAccessBlockCommand
GetBucketAnalyticsConfigurationCommand
GetBucketCorsCommand
GetBucketEncryptionCommand
GetBucketIntelligentTieringConfigurationCommand
GetBucketInventoryConfigurationCommand
GetBucketLifecycleConfigurationCommand
GetBucketLocationCommand
GetBucketLoggingCommand
GetBucketMetricsConfigurationCommand
GetBucketNotificationConfigurationCommand
GetBucketOwnershipControlsCommand
GetBucketPolicyCommand
GetBucketPolicyStatusCommand
GetBucketReplicationCommand
GetBucketRequestPaymentCommand
GetBucketTaggingCommand
GetBucketVersioningCommand
GetBucketWebsiteCommand
GetObjectAclCommand
GetObjectLegalHoldCommand
GetObjectLockConfigurationCommand
GetObjectRetentionCommand
GetObjectTaggingCommand
GetPublicAccessBlockCommand
HeadBucketCommand
HeadObjectCommand
ListBucketAnalyticsConfigurationsCommand
ListBucketIntelligentTieringConfigurationsCommand
ListBucketInventoryConfigurationsCommand
ListBucketMetricsConfigurationsCommand
ListMultipartUploadsCommand
ListObjectVersionsCommand
ListPartsCommand
PutBucketAccelerateConfigurationCommand
PutBucketAclCommand
PutBucketAnalyticsConfigurationCommand
PutBucketCorsCommand
PutBucketEncryptionCommand
PutBucketIntelligentTieringConfigurationCommand
PutBucketInventoryConfigurationCommand
PutBucketLifecycleConfigurationCommand
PutBucketLoggingCommand
PutBucketMetricsConfigurationCommand
PutBucketNotificationConfigurationCommand
PutBucketOwnershipControlsCommand
PutBucketPolicyCommand
PutBucketReplicationCommand
PutBucketRequestPaymentCommand
PutBucketTaggingCommand
PutBucketVersioningCommand
PutBucketWebsiteCommand
PutObjectAclCommand
PutObjectLegalHoldCommand
PutObjectLockConfigurationCommand
PutObjectRetentionCommand
PutObjectTaggingCommand
PutPublicAccessBlockCommand
UploadPartCommand
UploadPartCopyCommand
WriteGetObjectResponseCommand
useInsertLink putObject
copyObject
putObject
copyObject
RestoreObjectCommand
PutObjectCommand
CopyObjectCommand
useDeleteLink deleteBucket
deleteObject
deleteObjects
deleteBucket
deleteObject
deleteObjects
DeleteBucketCommand
DeleteObjectCommand
DeleteObjectsCommand
useSelectLink getObject
getObjectTorrent
listObjects
listObjectsV2
copyObject
getObject
getObjectTorrent
listObjects
listObjectsV2
copyObject
GetObjectCommand
ListObjectsCommand
ListObjectsV2Command
SelectObjectContentCommand
GetObjectTorrentCommand
CopyObjectCommand
useUpdateLink putBucketAnalyticsConfiguration putBucketAnalyticsConfiguration RestoreObjectCommand
PutObjectCommand
CopyObjectCommand

Example

This code will create an S3 Bucket named MyBucket and a useInsertLink to that bucket:

// Load the AWS SDK for Node.js
import * as AWS from 'aws-sdk'
// Set the region
AWS.config.update({region: 'REGION'});

// Create S3 service object
s3 = new AWS.S3({apiVersion: '2006-03-01'});

// Create the parameters for calling createBucket
var bucketParams = {
  Bucket : "MyBucket",
  ACL : 'public-read'
};

// call S3 to create the bucket
s3.createBucket(bucketParams, function(err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Location);
  }
});

params = {
    // ...
    Bucket: "MyBucket"
};
s3.putObject(params, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
});

This code will produce the following result:

AWS SQS

The following libraries are supported:

Library Import Supported Publisher APIs Supported Receiver APIs
AWS SDK V2 aws-sdk sendMessage
sendMessageBatch
receiveMessage
AWS SDK V3 @aws-sdk/client-sqs SendMessageCommand ReceiveMessageCommand

Example

This code will publish a message into the SQS_QUEUE_URL queue:

import * as AWS from "aws-sdk";
AWS.config.update({ region: 'REGION' });

const sqs = new AWS.SQS({apiVersion: '2012-11-05'});

const queueUrl = "SQS_QUEUE_URL"

const params = {
    MessageBody: "This is a message",
    QueueUrl: queueUrl,
    MaxNumberOfMessages: 1,
    VisibilityTimeout: 0,
};

class Foo {
  sendMessage(){
    sqs.sendMessage(params, function (err, data) {
        if (err) {
            console.log("Error", err);
        } else {
         console.log("Success", data.MessageId);
        }
    });
 }
}

This code will receive a message from the queue SQS_QUEUE_URL:

import * as AWS from "aws-sdk";
AWS.config.update({ region: 'REGION' });

const sqs = new AWS.SQS({apiVersion: '2012-11-05'});

const queueUrl = "SQS_QUEUE_URL"

const params = {
    QueueUrl: queueUrl,
    MaxNumberOfMessages: 1,
    VisibilityTimeout: 0,
};

export class SqsReciver {
    constructor() {
        this.reciver();
    }
    private reciver(): void {
        sqs.receiveMessage(params, (err, data) => {
    // do something
        });
    }
}

This code will produce the following result:

When the evaluation of the queue name fails, a NodeJS AWS SQS Unknown Publisher (or Receiver) will be created.

AWS DynamoDB

See DynamoDB support for Node.js source code - TypeScript for more information.

AWS X-Ray

AWS X-Ray encapsulates AWS method calls in order to provide status and load status.

Example

This code will encapsulate AWS SDK then create a dynamoDB instance, and a Table instance:

import AWSXRay from 'aws-xray-sdk-core'
import AWS from 'aws-sdk'
const AWS = AWSXRay.captureAWS(AWS) // Encapsulate AWS SDK
const DDB = new AWS.DynamoDB({ apiVersion: "2012-10-08" }) // use AWS as usual
const { v1: uuidv1 } = require('uuid');

// environment variables
const { TABLE_NAME, ENDPOINT_OVERRIDE, REGION } = process.env
const options = { region: REGION }
AWS.config.update({ region: REGION })

if (ENDPOINT_OVERRIDE !== "") {
    options.endpoint = ENDPOINT_OVERRIDE
}

const docClient = new AWS.DynamoDB.DocumentClient(options)
// response helper
const response = (statusCode, body, additionalHeaders) => ({
    statusCode,
    body: JSON.stringify(body),
    headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', ...additionalHeaders },
})

function addRecord(event) {
    let usernameField = {
        "cognito-username": getCognitoUsername(event)
    }

    // auto generated date fields
    let d = new Date()
    let dISO = d.toISOString()
    let auto_fields = {
        "id": uuidv1(),
        "creation_date": dISO,
        "lastupdate_date": dISO
    }

    //merge the json objects
    let item_body = {...usernameField, ...auto_fields, ...JSON.parse(event.body) }

    console.log(item_body);

    //final params to DynamoDB
    const params = {
        TableName: TABLE_NAME,
        Item: item_body
    }

    return docClient.put(params)
}

This code will produce the following result:

AWS Kinesis

Amazon Kinesisexternal link is a family of services provided by Amazon Web Services for processing and analyzing real-time streaming data at a large scale.

The following libraries are supported:

Library Import Supported Producer APIs Supported Consumer APIs
AWS SDK V2 aws-sdk putRecord
putRecords
getShardIterator
getRecords
AWS SDK V3 @aws-sdk/client-kinesis PutRecordCommand
PutRecordsCommand
GetShardIteratorCommand
GetRecordsCommand

The Web Services Linker will create a callLink between the Kinesis Producer and Kinesis Consumer which have the same stream name.

Example

API V2

When analyzing the following source code:

import * as AWS from 'aws-sdk';

const REGION = "us-east-1";
const kinesis = new AWS.Kinesis({ region: REGION });

const streamName = "data-stream-v2";

function putRecordFunction(): void {
  const params = {
    StreamName: streamName,
    Data: JSON.stringify({ message: "test data" }),
    PartitionKey: "partition1"
  };

  kinesis.putRecord(params, (err: any, data: any) => {
    if (err) console.error(err);
    else console.log(data);
  });
}

const getRecordsFunction = async (): Promise<void> => {
  const iteratorParams = {
    StreamName: streamName,
    ShardId: "shardId-000000000000",
    ShardIteratorType: "LATEST"
  };
  const iteratorData = await kinesis.getShardIterator(iteratorParams).promise();
  const recordsParams = {
    ShardIterator: iteratorData.ShardIterator
  };
  const data = await kinesis.getRecords(recordsParams).promise();
  console.log("Records", data.Records);
};

putRecordFunction();
getRecordsFunction();

The following results will be produced:

API V3

When analyzing the following source code:

import {
  KinesisClient,
  PutRecordCommand,
  GetShardIteratorCommand,
  GetRecordsCommand
} from "@aws-sdk/client-kinesis";

const REGION: string = "us-east-1";
const kinesisClient = new KinesisClient({ region: REGION });

const streamName = "data-stream-v3";

const putRecord = async (): Promise<void> => {
  const params = {
    StreamName: streamName,
    Data: new TextEncoder().encode(JSON.stringify({ message: "test data" })),
    PartitionKey: "partition1"
  };

  try {
    const data = await kinesisClient.send(new PutRecordCommand(params));
    console.log("Success", data.SequenceNumber);
  } catch (err) {
    console.error("Error", err);
  }
};

const getRecords = async (): Promise<void> => {
  try {
    const iteratorParams = {
      StreamName: streamName,
      ShardId: "shardId-000000000000",
      ShardIteratorType: "LATEST"
    };
    const iterator = await kinesisClient.send(new GetShardIteratorCommand(iteratorParams));
    const recordsParams = {
      ShardIterator: iterator.ShardIterator
    };

    const data = await kinesisClient.send(new GetRecordsCommand(recordsParams));
    console.log("Records", data.Records);
  } catch (err) {
    console.log("Error", err);
  }
};

putRecord();
getRecords();

The following results will be produced:

Known limitations

  • The use of AWS.SQS with promises is not supported. For instance, no link would be created between the receiver and the handler function defined in .then() call in the following source code:
    this.sqs.receiveMessage(params).promise().then( () => {})
    
  • If the queueName is set using the createQueue API, the evaluation of the queue name will fail.
  • Use of access points is not supported.