Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Supported Node.js versions

Dependencies with other extensions

Some CAST extensions require the presence of other CAST extensions in order to function correctly. The Node.js extension requires that the following other CAST extensions are also installed:

Info
Note that when using the CAST Extension Downloader to download the extension and the Manage Extensions interface in CAST Server Manager to install the extension, any dependent extensions are automatically downloaded and installed for you. You do not need to do anything.

Download and installation instructions

The extension will be automatically downloaded and installed in AIP Console (it is a "shipped" extension which means it is delivered with AIP Core). You can also manually install the extension using the Application - Extensions interface. When installed, follow the instructions below to run a new analysis/snapshot to generate new results:

Packaging, delivering and analyzing your source code

Once the extension is downloaded and installed, you can now package your source code and run an analysis. The process of packaging, delivering and analyzing your source code is described below:

...

What results can you expect?

Once the analysis/snapshot generation has completed, you can view the results in the normal manner (for example via CAST Enlighten):

Image Removed

Node.js application with MongoDB data storage exposing web services

Objects

The following specific objects are displayed in CAST Enlighten:

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Image Removed

...

Node.js Ecosystem

Node.js comes with numerous libraries and frameworks bringing data access, web services calls, microservices architectures. This list contains all supported libraries:

LibraryCommentData AccessWeb ServiceAWS.DynamoDBAmazon database access(tick)AWS.S3Amazon storage service(tick)AWS.LambdaAmazon routing solution(tick)CosmosDBMicrosoft Azure NoSQL Database solution(tick)CouchdbCouchdb access(tick)Couchdb-nanoCouchdb access(tick)elasticsearchOpen-source search engine (tick)ExpressNode.js application framework(tick)HapiNode.js application framework(tick)(tick)KnexNode.js SQL query builder (tick)KoaNode.js application framework(tick)LoopbackNode.js application framework(tick)(tick)MarklogicMarklogic access(tick)MemcachedStorage framework(tick)Mode-mongodb-nativeMongoDB access(tick)Mongo-clientMongoDB access(tick)MongooseMongoDB access(tick)my_connectionMySQL access(tick)Node-couchdbCouchdb access(tick)oracledbOracle Database access(tick)pgPostgreSQL access(tick)SailsNode.js application framework(tick)(tick)
VersionSupportComment
v0.x(error)No longer supported
v4.x(tick)LTS
v5.x(tick)Based on Javascript ES6
v6.x(tick)Based on Javascript ES6

v7.x

(tick)Based on Javascript ES6
v8.x(tick)
v9.x(tick)
v10.x(tick)
v11.x(tick)
v12.x(tick) 
v13.x(tick)
v14.x(tick)

Function Point, Quality and Sizing support

This extension provides the following support:

  • Function Points (transactions): a green tick indicates that OMG Function Point counting and Transaction Risk Index are supported
  • Quality and Sizing: a green tick indicates that CAST can measure size and that a minimum set of Quality Rules exist

...

Comparison with existing support for JavaScript

CAST AIP has provided support for analyzing JavaScript via its JEE and .NET analyzers (provided out of box in CAST AIP) for some time now. The HTML5/JavaScript extension (on which the Node.js extension depends) also provides support for JavaScript but with a focus on web applications. CAST highly recommends that you use this extension if your Application contains JavaScript and more specifically if you want to analyze a web application, however you should take note of the following:

  • You should ensure that you configure the extension to NOT analyze the back end web client part of a .NET or JEE application.
  • You should ensure that you configure the extension to ONLY analyze the front end web application built with the HTML5/JavaScript that communicates with the back end web client part of a .NET or JEE application.
  • If the back end web client part of a .NET or JEE application is analyzed with the Node.js extension and with the native .NET/JEE analyzers, then your results will reflect this - there will be duplicate objects and links (i.e. from the analyzer and from the extension) therefore impacting results and creating erroneous Function Point data.
Info

In CAST AIP 8.3.x support for analyzing JavaScript has been withdrawn from the JEE and .NET analyzers.

AIP Core compatibility

This extension is compatible with:

...

Supported

...

Supported DBMS servers

...

Prerequisites

...


v15.x(tick)
v16.x(tick)
v17.x(tick)

Node.js Ecosystem

Node.js comes with numerous libraries and frameworks bringing data access, web services calls, microservices architectures. This list contains all supported libraries:

LibraryCommentData AccessWeb ServiceMessaging
AWS.DynamoDBAmazon database access(tick)

AWS.S3Amazon storage service(tick)

AWS.SQSAmazon messaging service

(tick)
AWS.LambdaAmazon routing solution
(tick)
CosmosDBMicrosoft Azure NoSQL Database solution(tick)

CouchdbCouchdb access(tick)

Couchdb-nanoCouchdb access(tick)

elasticsearchOpen-source search engine (tick)

ExpressNode.js application framework
(tick)
HapiNode.js application framework(tick)(tick)
KnexNode.js SQL query builder (tick)

KoaNode.js application framework(tick)

LoopbackNode.js application framework(tick)(tick)
MarklogicMarklogic access(tick)

MemcachedStorage framework(tick)

Mode-mongodb-nativeMongoDB access(tick)

Mongo-clientMongoDB access(tick)

MongooseMongoDB access(tick)

MQTTMessaging library

(tick)
mssqlSQL server(tick)

my_connectionMySQL access(tick)

myssqlNodejs module to manipulate MySQL database


Node-couchdbCouchdb access(tick)

node-sqlserverSQL server(tick)

oracledbOracle Database access(tick)

pgPostgreSQL access(tick)

redisMongoDB access(tick)

SailsNode.js application framework(tick)(tick)
SenecaMicroservice toolkit
(tick)

Function Point, Quality and Sizing support

This extension provides the following support:

  • Function Points (transactions): a green tick indicates that OMG Function Point counting and Transaction Risk Index are supported
  • Quality and Sizing: a green tick indicates that CAST can measure size and that a minimum set of Quality Rules exist
Function Points
(transactions)
(tick)
Quality and Sizing(tick)

Comparison with existing support for JavaScript

CAST AIP has provided support for analyzing JavaScript via its JEE and .NET analyzers (provided out of box in CAST AIP) for some time now. The HTML5/JavaScript extension (on which the Node.js extension depends) also provides support for JavaScript but with a focus on web applications. CAST highly recommends that you use this extension if your Application contains JavaScript and more specifically if you want to analyze a web application, however you should take note of the following:

  • You should ensure that you configure the extension to NOT analyze the back end web client part of a .NET or JEE application.
  • You should ensure that you configure the extension to ONLY analyze the front end web application built with the HTML5/JavaScript that communicates with the back end web client part of a .NET or JEE application.
  • If the back end web client part of a .NET or JEE application is analyzed with the Node.js extension and with the native .NET/JEE analyzers, then your results will reflect this - there will be duplicate objects and links (i.e. from the analyzer and from the extension) therefore impacting results and creating erroneous Function Point data.
Info

In CAST AIP 8.3.x support for analyzing JavaScript has been withdrawn from the JEE and .NET analyzers.

AIP Core compatibility

This extension is compatible with:

AIP Core release
Supported
8.3.x(tick)

Supported DBMS servers

DBMSSupported?
CSS / PostgreSQL(tick)

Prerequisites

(tick)An installation of any compatible release of AIP Core (see table above)

Dependencies with other extensions

Some CAST extensions require the presence of other CAST extensions in order to function correctly. The Node.js extension requires that the following other CAST extensions are also installed:

Info
Note that when using the CAST Extension Downloader to download the extension and the Manage Extensions interface in CAST Server Manager to install the extension, any dependent extensions are automatically downloaded and installed for you. You do not need to do anything.

Download and installation instructions

The extension will be automatically downloaded and installed in AIP Console (it is a "shipped" extension which means it is delivered with AIP Core). You can also manually install the extension using the Application - Extensions interface. When installed, follow the instructions below to run a new analysis/snapshot to generate new results:

Packaging, delivering and analyzing your source code

Once the extension is downloaded and installed, you can now package your source code and run an analysis. The process of packaging, delivering and analyzing your source code is described below:

Expand

Include Page
Node.js - Packaging, delivering and analyzing your source code
Node.js - Packaging, delivering and analyzing your source code

What results can you expect?

Once the analysis/snapshot generation has completed, you can view the results in the normal manner (for example via CAST Enlighten):

Image Added

Node.js application with MongoDB data storage exposing web services

Objects

The following specific objects are displayed in CAST Enlighten:

IconDescription

Image Added

Node.js Application

Image Added

Node.js Port

Image Added

Node.js Delete Operation Service

Image Added

Node.js Get Operation Service
Image Added
Node.js Post Operation Service
Image Added
Node.js Put Operation Service

Image Added

Node.js Service

Image Added

Node.js Express Use

Image Added

Node.js Express Controller

Image Added

Node.js Get Http Request Service

Image Added

Node.js Post Http Request Service

Image Added

Node.js Put Http Request Service

Image Added

Node.js Delete Http Request Service

Image Added

Node.js Unknown Database

Image Added

Node.js Collection

Image Added

Node.js Memcached Connection

Image Added

Node.js Memcached Value

Image Added

Node.js Call to Java Program

Image Added

Node.js Call to Generic Program

Image Added

Node.js Restify Get Operation

Image Added

Node.js Restify Post Operation

Image Added

Node.js Restify Put Operation

Image Added

Node.js Restify Delete Operation

Image Added

Node.js AWS SQS Publisher

Image Added

Node.js AWS SQS Receiver

Image Added

Node.js AWS SQS Unknown Publisher

Image Added

Node.js AWS SQS Unknown Receiver

Image Added

Node.js AWS SNS Publisher

Image Added

Node.js AWS SNS Subscriber

Image Added

Node.js AWS SNS Unknown Publisher

Image Added

Node.js AWS SNS Unknown Subscriber

Image Added

Node.js AWS call to Lamba Function

Image Added

Node.js AWS call to unknown Lambda Function

External link behavior

Behaviour is different depending on the version of CAST AIP you are using the extension with:

...

Anchor
AWS
AWS
Amazon Web Services (AWS)

...

Anchor
AWSLambda
AWSLambda
Support for lambda

In AWS, the event_type can be more specific by adding information after the semicolon. However, the analyzer does not consider this information. For instance, it will make no distinction between ObjectCreated:* and ObjectCreated:Put or ObjectCreated:Post event types.Lambda services allow executing some source code on the cloud. The execution can be set to be triggered by some AWS events. 

Lambda functions can be deployed using several deployment frameworks. The supported deployment frameworks are listed on this page.

When a lambda function is created and its runtime is java, the current extension is responsible for linking the lambda objects and their triggers with the java handler functions.

Example

Let us consider a source code defining a lambda function that has two triggers: an SQS queue and an API Gateway. The lambda function has a java runtime (for instance java8) and the handler function is given by the handler function fullname. 

If the lambda function is deployed using a supported deployment framework (such as CloudFormation), the analysis will create a lambda function, an SQS receiver, and an API Gateway objects. Each of these objects has a runtime property (java8) and a handler property with the function fullname. 

If the current extension finds a java method matching the handler fullname a link to that java method will be added from the lambda function, the SQS queue and the API Gateway objects.Image Added


Expand

Supported deployment frameworks

Serverless framework, Serverless Application Model (SAM) and Cloudformation are supported. They are frameworks using *.yml or *.json file to set up AWS environment.

Lambda creation

This example comes from https://github.com/zanon-io/aws-serverless-demo. In serverless.yml:

Code Block
languageyml
service: my-serverless-demo
provider:
  name: aws
  runtime: nodejs4.3
  region: us-east-1
  iamRoleStatements:
    - Effect: "Allow"
      Action:
        - 'sdb:Select'
      Resource: "arn:aws:sdb:${self:provider.region}:*:domain/Weather"
functions:
  weather:
    handler: handler.currentTemperature
    events:
      - http: GET weather/temperature
      - http: POST weather/temperature
    memorySize: 128
    timeout: 10
  meanweather:
    handler: handler.meanTemperature
    events:
      - http:
          path: weather/temperature/mean
          method: get
    memorySize: 128
    timeout: 10
    runtime: java

In handler.js:

Code Block
languagejs
linenumberstrue
module.exports.currentTemperature = (event, context, callback) => {

  const response = {
    statusCode: 200,
    body: JSON.stringify({
      temperature: 30,
      locationId: event.id
    })
  };

  callback(null, response);
};

In index.html:

Code Block
languagejs
linenumberstrue
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Weather Info</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <style TYPE="text/css">
      input[type=button] {
        margin: 10px 0px;
      }
      p {
        margin: 10px 0px;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-xs-offset-4 col-xs-4 col-sm-offset-4 col-sm-3 col-md-offset-5 col-md-2 pagination-centered text-center">
          <h3>Daily Weather</h3>
          <input id="btn-show" type="button" class="btn btn-primary" value='Show Current'>
        </div>
      </div>
      <div class="row">
        <div class="col-xs-offset-4 col-xs-4 col-sm-offset-4 col-sm-3 col-md-offset-5 col-md-2">
          <p>Value: <span id="weather-value"></span></p>
          <a href="http://zanon.io/posts/building-serverless-websites-on-aws-tutorial"><p>source</p></a>
        </div>
      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script>
      $(document).ready(function() {

        $('#btn-show').on('click', function() {

            $.ajax({
              url: "https://8w8ctjxkeh.execute-api.us-east-1.amazonaws.com/dev/weather/temperature?id=5", // Here is the GET request
              success: function(json) {
                $("#weather-value").text(json.temperature + ' ºC').fadeOut('slow').fadeIn('slow');
              }
            });
        });
      });
    </script>
  </body>
</html>

What results can you expect?

Once the analysis/snapshot generation has completed, you can view the results in the normal manner (for example via CAST Enlighten):

Click to enlarge

Image Removed

Lambda triggers

The lambda can be triggered by several kind of events. The following event types are supported. 

ApiGateway

The analyzer creates an AWS Lambda operation with a call link to the handler of the function as documented in the previous section (lambda creation)

SQS

A lambda function can be set to be executed whenever a message is sent to a given SQS queue. For instance, with the following serverless framework file the mylambda function will be executed when a message is sent to the MyQueue SQS queue.

Code Block
languageyml
linenumberstrue
functions:
  mylambda:
    handler: com.amazonaws.example.serverless.Handler
    events:
      - sqs:
          arn:
            Fn::GetAtt:
              - MyQueue
              - Arn          
 
 
resources:
  Resources:
    MyQueue:
      Type: "AWS::SQS::Queue"
      Properties:
        QueueName: "MyQueue"

The analyzer creates a NodeJS AWS Simple Queue Service Receiver object linked to the handler of the lambda:

Image Removed 

The com.castsoftware.wbslinker would then link any SQS Publisher object (created by any extension) with the same queue name to that AWS Simple Queue Service Receiver object.

S3

A lambda function can be set to be executed whenever a given event on a given S3 bucket happens. For instance, with the following serverless framework file the mylambda function will be executed when an object is created in the Bucket1 S3 bucket.

Code Block
languageyml
linenumberstrue
functions:
  mylambda:
    handler: handler.apilambda
    events:
      - s3:
          bucket: Bucket1  #bucket name
          event: s3:ObjectCreated:*

The analyzer will create a call link to the lambda from all callables linked to Bucket1 through a useInsert link.

Image Removed

The following table tells which link type will match which event type.

event_type

matching link types

No event_typeall 
ObjectCreateduseInsert
ObjectRemoveduseDelete
ObjectRestoreNone
ReducedRedundancyLostObjectNone
ReplicationNone

Anchor
AWSSQS
AWSSQS
Support for SQS

...

Code Block
languagejs
linenumberstrue
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region 
AWS.config.update({region: 'REGION'});

// Create an SQS service object
var sqs = new AWS.SQS({apiVersion: '2012-11-05'});

var params = {
   // Remove DelaySeconds parameter and value for FIFO queues
  DelaySeconds: 10,
  MessageAttributes: {
    "Title": {
      DataType: "String",
      StringValue: "The Whistler"
    },
    "Author": {
      DataType: "String",
      StringValue: "John Grisham"
    },
    "WeeksOn": {
      DataType: "Number",
      StringValue: "6"
    }
  },
  MessageBody: "Information about current NY Times fiction bestseller for week of 12/11/2016.",
  // MessageDeduplicationId: "TheWhistler",  // Required for FIFO queues
  // MessageGroupId: "Group1",  // Required for FIFO queues
  QueueUrl: "SQS_QUEUE_URL"
};

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

What results can you expect?

Once the analysis/snapshot generation has completed, you can view the results in the normal manner (for example via CAST Enlighten):

...

Link TypeFunction
No Link
  • createBucket
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

  • upload

  • uploadPart

  • uploadPartCopy

useInsertLink
  • putObject
useDeleteLink
  • deleteBucket
  • deleteObject

  • deleteObjects

useSelectLink
  • getObject
  • getObjectTorrent
  • listObjects

  • listObjectsV2

useUpdateLink
  • putBucketLogging
  • putBucketAnalyticsConfiguration

Code samples

This code will create a S3 Bucket named "MyBucket" on an AWS server in region "REGION" and puts an object in it

Code Block
languagejs
linenumberstrue
// Load the AWS SDK for Node.js
var AWS = require('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
});

What results can you expect?

Once the analysis/snapshot generation has completed, you can view the results in the normal manner (for example via CAST Enlighten):

Image Removed

Analysis of the code sample

...

  • 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: 
Code Block
languagexml
sqs.receiveMessage(params).promise().then( () => {});
  • The use of AWS.SQS with send() is not supported. For instance no link would be created between the receiver and the handler function defined in .send() call in the following source code: 
Code Block
languagexml
var request = sqs.receiveMessage(params);
request.send(() => {});

Support for SNS

The following APIs are supported:

For SDK V2

  • AWS.SNS({apiVersion: '2010-03-31'}).publish(params)
  • AWS.SNS({apiVersion: '2010-03-31'}).subscribe(params)

For the publish method a NodeJS AWS SNS Publisher object is created. Its name is that of the topic.

For the subscribe methods, a NodeJS AWS 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 supported protocols are the following:

...

the com.castsoftware.wbslinker will create a callLink between the SNS Publishers and SNS Subscribers which have the same name.

Example

When analyzing the following source code:

...

languagejs

...

Code samples

This code will create a S3 Bucket named "MyBucket" on an AWS server in region "REGION" and puts an object in it

Code Block
languagejs
linenumberstrue
// Load the AWS SDK for Node.js
var AWS = require('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
});

What results can you expect?

Once the analysis/snapshot generation has completed, you can view the results in the normal manner (for example via CAST Enlighten):

Image Added

Analysis of the code sample

Anchor
KnownLimitationAWS
KnownLimitationAWS
Known limitations for AWS support
  • 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: 
Code Block
languagexml
sqs.receiveMessage(params).promise().then( () => {});
  • The use of AWS.SQS with send() is not supported. For instance no link would be created between the receiver and the handler function defined in .send() call in the following source code: 
Code Block
languagexml
var request = sqs.receiveMessage(params);
request.send(() => {});

Support for SNS

The following APIs are supported:

For SDK V2

  • AWS.SNS({apiVersion: '2010-03-31'}).publish(params)
  • AWS.SNS({apiVersion: '2010-03-31'})

...

  • .subscribe(params)

For the publish method a NodeJS AWS SNS Publisher object is created. Its name is that of the topic.

For the subscribe methods, a NodeJS AWS 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 supported protocols are the following:

protocolobject createdname of the object
emailNodeJS Emailan Email   (the email addresses are not evaluated)
smsNodeJS SMSan SMS   (the SMS numbers are not evaluated)
http/httpsNodeJS AWS Post HttpRequers servicethe url (evaluated from the endpoint)
sqsNodeJS AWS Simple Queue Service Publisherthe name of the queue (evaluated from the endpoint)
lambdaNodeJS Call to AWS Lambda Functionthe name of the lambda function (evaluated from the endpoint)

the com.castsoftware.wbslinker will create a callLink between the SNS Publishers and SNS Subscribers which have the same name.


Example

When analyzing the following source code:

Code Block
languagejs
var AWS = require('aws-sdk');
// Set region
AWS.config.update({region: 'REGION'});
// Create promise and SNS service object

var sns = new AWS.SNS({apiVersion: '2010-03-31'})

function my_subscribe(params) {
    sns.subscribe(params, function (err, data) {
        if (err) console.log(err, err.stack); // an error occurred
        else console.log(data);           // successful response
    });
}

function my_publish(params) {
    sns.publish(params);
}

function foo() {
    let topicArn = "arn:aws:sns:eu-west-3:757025016730:testTopic1testTopic",;
//TOPIC_ARN    my_subscribe({Protocol: "EMAIL", TopicArn:  topicArn, Endpoint: "007", //EMAIL_ADDRESS
    };"})
    my_subscribe_and_publish(params3)
}

function toto4() {
    const params4 = {
        Protocol: "LAMBDA" /* required */SMS", TopicArn: topicArn, Endpoint: "911"})
    TopicArnmy_subscribe({Protocol: "arn:aws:sns:eu-west-3:757025016730:testTopic2LAMBDA", //TOPIC_ARN
       TopicArn: topicArn, Endpoint: "arn:aws:lambda:eu-west-3:757025016730:testLambda", //EMAIL_ADDRESS})
     };
    my_subscribe_and_publish(params4)my_subscribe({Protocol: "HTTP", TopicArn: topicArn, Endpoint: "http:/myapi.api.test.com"})
 }
function toto5bar() {
    const params5 = {
        Protocol: "HTTP" /* required */,params2 = {
        TopicArn: "arn:aws:sns:eu-west-3:757025016730:testTopic1testTopic",
//TOPIC_ARN         EndpointMessage: "http:/myapi.api.test.com", //EMAIL_ADDRESS
MESSAGE_TEXT"
    };
    my_subscribe_and_publish(params5params2)
}

Image RemovedImage Added



Linking

The extension com.castsoftware.wbslinker is responsible for matching NodeJS Call to AWS Lambda Function objects to Lambda Function objects such as Java AWS Lambda Function during application-level analysis.

...

Code Block
languagejs
linenumberstrue
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0

// default imports
const AWSXRay = require('aws-xray-sdk-core')
const AWS = AWSXRay.captureAWS(require('aws-sdk')) // Encapsulate AWS SDK
const { metricScope, Unit } = require("aws-embedded-metrics")
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 isValidRequest(context, event) {
    return (event.body !== null)
}

function getCognitoUsername(event){
    let authHeader = event.requestContext.authorizer;
    if (authHeader !== null)
    {
        return authHeader.claims["cognito:username"];
    }
    return null;

}

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)
}

// Lambda Handler
exports.addToDoItem =
    metricScope(metrics =>
        async (event, context, callback) => {
            metrics.setNamespace('TodoApp')
            metrics.putDimensions({ Service: "addTodo" })
            metrics.setProperty("RequestId", context.requestId)

            if (!isValidRequest(context, event)) {
                metrics.putMetric("Error", 1, Unit.Count)
                return response(400, { message: "Error: Invalid request" })
            }

            try {
                let data = await addRecord(event).promise()
                metrics.putMetric("Success", 1, Unit.Count)
                return response(200, data)
            } catch (err) {
                metrics.putMetric("Error", 1, Unit.Count)
                return response(400, { message: err.message })
            }
        }
    )

What results can you expect?

Once the analysis/snapshot generation has completed, you can view the results in the normal manner (for example via CAST Enlighten):

...

Code Block
languagejs
linenumberstrue
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0

// default imports
const AWSXRay = require('aws-xray-sdk-core')
const AWS = AWSXRay.captureAWS(require('aws-sdk')) // Encapsulate AWS SDK
const { metricScope, Unit } = require("aws-embedded-metrics")
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 isValidRequest(context, event) {
    return (event.body !== null)
}

function getCognitoUsername(event){
    let authHeader = event.requestContext.authorizer;
    if (authHeader !== null)
    {
        return authHeader.claims["cognito:username"];
    }
    return null;

}

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)
}

// Lambda Handler
exports.addToDoItem =
    metricScope(metrics =>
        async (event, context, callback) => {
            metrics.setNamespace('TodoApp')
            metrics.putDimensions({ Service: "addTodo" })
            metrics.setProperty("RequestId", context.requestId)

            if (!isValidRequest(context, event)) {
                metrics.putMetric("Error", 1, Unit.Count)
                return response(400, { message: "Error: Invalid request" })
            }

            try {
                let data = await addRecord(event).promise()
                metrics.putMetric("Success", 1, Unit.Count)
                return response(200, data)
            } catch (err) {
                metrics.putMetric("Error", 1, Unit.Count)
                return response(400, { message: err.message })
            }
        }
    )

What results can you expect?

Once the analysis/snapshot generation has completed, you can view the results in the normal manner (for example via CAST Enlighten)

...

The following structural rules are provided:

Known Limitations

In this section we list the most significant functional limitations that may affect the analysis of applications using Node.js:

...