Levee, circuit breaker pattern, throwing an exception when it is executed - node.js

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)

Related

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

Blinking led light using nodejs

I am performing my first IOT project hello world blinking I'm trying to started with web of things book and having a problem.
The book is this: https://webofthings.org/2016/10/23/node-gpio-and-the-raspberry-pi/.
But When I trying to run the code I get the error.
/home/pi/Desktop/hello_world/node_modules/onoff/onoff.js:9 const HIGH_BUF = Buffer.from('1');
TypeError: this is not a typed array.
at Function.from (native)
at Object.<anonymous>
(/home/pi/Desktop/faizan/node_modules/onoff/onoff.js:9:25)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/home/pi/Desktop/faizan/app.js:1:75)
at Module._compile (module.js:409:26)
The code I'm running is
var onoff = require('onoff');
var Gpio = onoff.Gpio,
led = new Gpio(4,'out'),
interval;
interval = setInterval(function (){
var value = (led.readSync() + 1) % 2;
led.write(value, function() {
console.log("Changed LED state to: " + value);
});
}, 2000);
process.on('SIGINT', function () {
clearInterval(interval);
led.writeSync(0);
led.unexport();
console.log('Bye, bye!');
process.exit();
});

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

DynamoDB causing module initialization error in Node/Lambda

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

How to set a model to a variable in loopback?

fallowing code returns list of models
var models = app.models();
models.forEach(function(Model) {
console.log(Model.modelName);
});
User
AccessToken
ACL
RoleMapping
Role
Registration
Assets
when I using fallowing code to use Registration or Asstes:
D:\apps\newapps\testapp\node_modules\loopback\lib\application.js:129
assert(Model.prototype instanceof Model.registry.getModel('Model'),
^
TypeError: Cannot read property 'prototype' of undefined
at Function.app.model (D:\apps\newapps\testapp\node_modules\loopback\lib\application.js:129:17)
at Object.<anonymous> (D:\apps\newapps\testapp\server\server.js:38:5)
at Module._compile (module.js:573:30)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Function.Module.runMain (module.js:609:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:598:3
I am not expert of loopback but try this code:
var Registration = app.models.Registration;
console.log(Registration);
app.model(Registration);
User is the model name.
var user = app.models.User;
resetPassword is function name of the user model, which
take two parameter new_pwd and token,
user.resetPassword({
new_pwd: new_password,
token
}, (err, data) => {
if (err || !data.status) {
return err || data;
} else {
return data;
}
});

Resources