DynamoDB causing module initialization error in Node/Lambda - node.js

For clarity, this takes place in a Node 6.10 AWS Lambda function.
Error:
module initialization error: Error
at Object.Service (/var/task/node_modules/aws-sdk/lib/service.js:24:28)
at Object.features.constructor [as DynamoDB] (/var/task/node_modules/aws-sdk/lib/util.js:602:24)
at Object.<anonymous> (/var/task/web.js:4:22)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
The module's initialisation:
const aws = require('aws-sdk');
this.dynamoDb = new aws.DynamoDB();
Not sure what to do here; missing something obvious?

Please try,
var AWS = require("aws-sdk");
//If you are running in Lambda you don't need below AWS.config section
AWS.config.update({
region: "REGION"
});
var docClient = new AWS.DynamoDB.DocumentClient();
and use 'docClient' to access DynamoDB functions.
For example,
docClient.put(params, function (err, data) {
if (err) {
console.error("Unable to add item. Error JSON:", JSON.stringify(err,null, 2));
} else {
callback(null, "Error while adding data:", JSON.stringify(data, null, 2))
}
});
Please find the sample I have created in my GitHub :- https://github.com/vnathv/DynamoDb-CRUD.git

Related

TypeError: Cannot read properties of undefined (reading 'getBalance') in node.js

I am getting error when using web3.js to get the balance of an account. I am using ganache. My code is below,
var Web3 = require("web3");
//connect with ganache
const ganacheWeb3 = new Web3(
new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545")
);
console.log(ganacheWeb3);
//check the balance of an account
const balanceOfAccount = Web3.Eth.getBalance(
"0xaEA4e665291fdBFe4bAFc5b81F6F213551180ab5"
);
console.log(
balanceOfAccount.then((result) =>
console.log(Web3.utils.fromWei(result, "ether"))
)
);
Web3.eth.getBalance(
"0xaEA4e665291fdBFe4bAFc5b81F6F213551180ab5",
(error, result) => {
if (error) {
console.log(error);
} else {
console.log(result);
}
}
);
I have used the normal functional way and callback way. I don't know which one is correct. But still I am getting error. The error is,
const balanceOfAccount = Web3.Eth.getBalance(
^
TypeError: Cannot read properties of undefined (reading 'getBalance')
at Object.<anonymous> (D:\Blockchain Development\Web3.js\intro-to-web3.js\index.js:10:35)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)
at node:internal/main/run_main_module:23:47
I am trying to get the value of an ethereum account. But getting an error.
Change Web3.Eth.getBalance(...) to Web3.eth.getBalance(...).
Documentation: https://web3js.readthedocs.io/en/v1.2.11/web3-eth.html#getbalance

JS- why is context not passed in to child function?

I am trying to declare a logger object, then have a child function write to the log that was declared in the parent using the context. However the context appears to be undefined inside the children, whether I use an arrow function or not.
Is it possible to pass the winston object to the child function implicitly ie without having to pass a winston object as a parameter?
Error log output:
this main context: {}
undefined
l1 err: TypeError: Cannot read properties of undefined (reading 'winston')
at l1 (MYPATH\cw_log_test_helper.ts:4:19)
at run (MYPATH\cw_log_contexts.ts:30:7)
at Object.<anonymous> (MYPATH\cw_log_contexts.ts:39:1)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Module.m._compile (MYPATH\node_modules\ts-node\src\index.ts:1371:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Object.require.extensions.<computed> [as .ts] (MYPATH\node_modules\ts-node\src\index.ts:1374:12)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
{ l1: [Function: l1], r1: [AsyncFunction: r1] }
r1 err: TypeError: Cannot read properties of undefined (reading 'error')
at r1 (MYPATH\cw_log_test_helper.ts:12:31)
at run (MYPATH\cw_log_contexts.ts:31:7)
at Object.<anonymous> (MYPATH\cw_log_contexts.ts:39:1)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Module.m._compile (MYPATH\node_modules\ts-node\src\index.ts:1371:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Object.require.extensions.<computed> [as .ts] (MYPATH\node_modules\ts-node\src\index.ts:1374:12)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
bye
main.ts
var winston=require('winston');
var WinstonCloudWatch=require('winston-cloudwatch');
import { l1, r1 } from './cw_log_test_helper';
const AWS = require('aws-sdk');
AWS.config.update({
region: 'us-east-1',
});
var run=()=>{
let sname=`mylambda`
var self=winston.add(new WinstonCloudWatch({
name:sname,
cloudWatchLogs: new AWS.CloudWatchLogs(),
logGroupName: 'winston-testing',
logStreamName: sname
}));
console.log(`this main context:`,this)
winston.error('first'); //<<<<<<<<<<<<<<<<<<WORKS
l1(`hello`) //<<<<<<<<<<<<<<<<FAILS
r1('hi') //<<<<<<<<<<<<<<<<FAILS
// flushes the logs and clears setInterval
var transport = self.transports.find((t) => t.name === sname)
transport.kthxbye(function() {
console.log('bye');
});
}
run()
cw_log_test_helper.ts:
export var l1=function(ltxt:string){
console.log(this)
try{
(this as any).winston.error(ltxt);
}catch(e){
console.log(`l1 err:`,e)
}
}
export var r1 = async (ltxt:string) => {
console.log(this)
try{
(this as any).winston.error(ltxt);
}catch(e){
console.log(`r1 err:`,e)
}
}

Levee, circuit breaker pattern, throwing an exception when it is executed

I am new to the Node.js and I came across levee which is used as circuit breaker, when I execute the following code, The exception occurs
'use strict';
var Levee = require('levee');
var Wreck = require('wreck');
var options, circuit;
options = {
maxFailures: 5,
timeout: 60000,
resetTimeout: 30000
};
circuit = Levee.createBreaker(Wreck.get, options);
circuit.run('https://www.google.com', function (err, req, payload)
{
// If the service fails or timeouts occur 5 consecutive times,
// the breaker opens, fast failing subsequent requests.
console.log(err || payload);
});
And the Exception is as follows
TypeError: this._shortcut is not a function
at Object.internals.Client.get [as execute] (/Users/amolmohandeshpande/Documents/node/node_modules/wreck/lib/index.js:580:17)
at zalgo (/Users/amolmohandeshpande/Documents/node/node_modules/levee/lib/zalgo.js:28:12)
at Breaker._run (/Users/amolmohandeshpande/Documents/node/node_modules/levee/lib/breaker.js:126:13)
at Breaker.run (/Users/amolmohandeshpande/Documents/node/node_modules/levee/lib/breaker.js:60:15)
at Object. (/Users/amolmohandeshpande/Documents/node/server.js:15:9)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)

Azure Chatbot fails with "SyntaxError: Unexpected identifier - cosmosClient.databases.createIfNotExists" while connecting to CosmosDB

I am extremely new to Azure Bot Services and the Azure platform as a whole.
I am trying to create a Chatbot using node.js but I am getting the below error while trying to connect to CosmosDB.
The bot was running fine before I added the below code to connect to CosmosDB.
Any help or guidance on this would be appreciated!
P.S. - I have added the '#azure/cosmos' package and the code runs without any error if I just remove the try-catch segment.
Code for connecting to CosmosDB:
var async=require("async");
var await=require("await");
const CosmosClientInterface = require("#azure/cosmos").CosmosClient;
const databaseId = "ToDoList";
const containerId = "custInfo";
const endpoint = "<Have provided the Endpoint URL here>";
const authKey = "<Have provided the AuthKey here>";
const cosmosClient = new CosmosClientInterface({
endpoint: endpoint,
auth: {
masterKey: authKey
},
consistencyLevel: "Session"
});
async function readDatabase() {
const { body: databaseDefinition } = await cosmosClient.database(databaseId).read();
console.log(`Reading database:\n${databaseDefinition.id}\n`);
}
Error Message:
Sat Jan 12 2019 03:40:08 GMT+0000 (Coordinated Universal Time): Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\app.js:40
async function readDatabase() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Program Files (x86)\iisnode\interceptor.js:459:1)
at Module._compile (module.js:570:32)
Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\app.js:40
async function readDatabase() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Program Files (x86)\iisnode\interceptor.js:459:1)
at Module._compile (module.js:570:32)
You can't await without being in an async function.
Dump all your code into a async function main(){} method, then call main().catch((err) => console.log(err)); or some similar thing to start the promise and handle errors.
You can see a sample of that kind of pattern here in this sample: https://github.com/Azure/azure-cosmos-js/blob/master/samples/ChangeFeed/app.js#L33
--- EDIT 1 ---
Here's your sample rewritten with Promises:
const CosmosClientInterface = require("#azure/cosmos").CosmosClient;
const databaseId = "ToDoList";
const containerId = "custInfo";
const endpoint = "<Have provided the Endpoint URL here>";
const authKey = "<Have provided the AuthKey here>";
const cosmosClient = new CosmosClientInterface({
endpoint: endpoint,
auth: {
masterKey: authKey
},
consistencyLevel: "Session"
});
cosmosClient.database(databaseId).read().then(({body: databaseDefinition}) => {
console.log(`Reading database:\n${databaseDefinition.id}\n`);
}).catch((err) {
console.err("Something went wrong" + err);
});
For your sample above, you don't need to import async/await, they are keywords in JavaScript now.
Here's a blog post that compares and contrasts Async/Await and Promises: https://hackernoon.com/should-i-use-promises-or-async-await-126ab5c98789

RestClient has been removed from this version of the library (TWILIO)

throw new Error(this.constructor.name + ' has been removed from this
version of the library. Please refer to
https://www.twilio.com/docs/libraries/node for more information.')
^ Error: RestClient has been removed from this version of the library. Please refer to https://www.twilio.com/docs/libraries/node
for more information.
at RestClient.ObsoleteClient (C:\carsapp\node_modules\twilio\lib\base\obsolete.js:7:9)
at new RestClient (C:\carsapp\node_modules\twilio\lib\base\obsolete.js:12:21)
at Object. (C:\carsapp\helpers\twilio_restful_client_connection.ts:6:34)
at Module._compile (module.js:643:30)
at Module.m._compile (C:\Users\Andrey Radkevich\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:422:23)
at Module._extensions..js (module.js:654:10)
at Object.require.extensions.(anonymous function) [as .ts] (C:\Users\Andrey
Radkevich\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:425:12)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at Object. (C:\carsapp\helpers\sing-in-up-helper.ts:8:1)
at Module._compile (module.js:643:30)
at Module.m._compile (C:\Users\Andrey Radkevich\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:422:23)
at Module._extensions..js (module.js:654:10)
const accountSid = 'AC2a54bb2c4ea4992593cc9f0ca2f720c0';
const authToken = 'your_auth_token';
const Client = require('twilio').RestClient;
const client = new Client(accountSid, authToken);
client.outgoingCallerIds.create(
{
friendlyName: 'My Home Phone Number',
phoneNumber: '+14158675310',
},
(err, callerId) => {
if (err) {
console.error(err);
} else {
console.log(callerId.sid);
}
}
);
I have got this error when I tried to create this part of the code above. I tried to add a number to Twilio whitelist ( verify phone number).How can I make it in another way? I use for this Node js
Link on this part of the code in the documentation :
https://www.twilio.com/docs/api/voice/outgoing-caller-ids
const accountSid = 'AC2a54bb2c4ea4992593cc9f0ca2f720c0';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.validationRequests
.create({
friendlyName: 'My Home Phone Number',
phoneNumber: '+14158675310',
})
.then(data => console.log(data.validationCode));
https://www.twilio.com/docs/api/voice/outgoing-caller-ids#add-an-outgoing-caller-id
Here answer on my own question

Resources