redis port and host undefined even though env are set - javascript

I am using the redis npm package and whenever I try to connect to it, it's saying the host and port are undefined. I print out my process.env object and I can see that the host and port have values set. It's only when I pass the values into my constructor for my Redis model class, that it becomes undefined. Any ideas?
index.js
require('dotenv').config()
function startRedis() {
const redisInstance = new Redis(
process.env.REDIS_HOST,
process.env.REDIS_PORT
);
redisInstance.init();
}
class Redis {
constructor(redishost, redisport) {
this.redishost = redishost;
this.redisport = redisport;
}
async init() {
try {
this.redisClient = redis.createClient({
port: this.redisport,
host: this.redishost
});
console.log("port: ", this.port)
console.log("host: ", this.host)
} catch(error) {
console.log(`Error creating client due to: ${error}`)
}
}
.env
REDIS_HOST="value here"
REDIS_PORT="port value here"
package.json
{
"name": "app",
"version": "0.0.1",
"dependencies": {
"redis": "^3.0.2",
"dotenv": "^10.0.0"
},
"engines": {
"node": ">=10.0.0"
},
"main": "index.js",
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"redis": "^3.0.2",
"dotenv": "^10.0.0"
}
}
Update 1: Added my package.json

As I can see here if process.env.REDIS_HOST having value.
You have new on wrong class name
Your start function should be like
function startRedis() {
const redisInstance = new Redis(
process.env.REDIS_HOST,
process.env.REDIS_PORT
);
redisInstance.init();
}
And you are console.log wrong value
class Redis {
constructor(redishost, redisport) {
this.redishost = redishost;
this.redisport = redisport;
}
async init() {
try {
this.redisClient = redis.createClient({
port: this.redisport,
host: this.redishost
});
console.log("port: ", this.redisport)
console.log("host: ", this.redishost)
} catch(error) {
console.log(`Error creating client due to: ${error}`)
}
}

Related

Capacitor / Cordova EmmAppConfig plugin with Javascript

I'm trying to get the following working based on this post "Building a CapacitorJS application using pure JavaScript and Webpack" on Medium.com (https://medium.com/#SmileFX/a-complete-guide-building-a-capacitorjs-application-using-pure-javascript-and-webpack-37d00f11720d)
My intention is to build an Android app that will get deployed from an MDM server with an AppConfig configuration. When launched, the app will generate a file (derived from the AppConfig configuration) and save the file to the file system on the device.
Here is the content of my index.js
import '#capacitor/core';
import '#angular/core';
import '#ionic-native/core';
import 'rxjs';
import { Device } from '#capacitor/device';
import { Filesystem, Directory, Encoding } from '#capacitor/filesystem';
//import { EmmAppConfig } from '#ionic-native/emm-app-config/ngx';
async function getDeviceInfo() {
message("getDeviceInfo started");
let info = await Device.getInfo();
return info.operatingSystem;
}
async function getEmmAppConfig() {
message("getEmmAppConfig started");
//let eac = await EmmAppConfig.getValue("z_number");
let eac = "Z_1234_567";
return eac;
};
async function putFile(name, data) {
message("putFile started with name: " +name+ " and data: " +data);
let file = await Filesystem.writeFile({
path: "file:///storage/emulated/0/z_number/" +name+ ".txt",
data: data,
recursive: true,
encoding: Encoding.UTF8
});
return file;
};
window.onload = start;
function start() {
message("app started");
getDeviceInfo().then(info => {
putFile("info", info).then(file => {
message("File saved here: " +JSON.stringify(file, null, 4));
});
});
getEmmAppConfig().then(eac => {
putFile("eac", eac).then(file => {
message("File saved here: " +JSON.stringify(file, null, 4));
});
});
}
function message(message) {
document.body.innerHTML = document.body.innerHTML+ "<p>" +message+ "</p>" ;
}
The above code does run on the Android emulator and saves bothe files as expected only when "import { EmmAppConfig } from '#ionic-native/emm-app-config/ngx';" is commented out, otherwise it does not run (not even to output "App Started")
this is the content of my package.json
{
"name": "capacitor-app",
"version": "1.0.0",
"description": "An Amazing Capacitor App",
"main": "index.js",
"keywords": [
"capacitor",
"mobile"
],
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"#angular/core": "^13.0.3",
"#capacitor/android": "^3.3.2",
"#capacitor/camera": "latest",
"#capacitor/core": "latest",
"#capacitor/device": "^1.1.0",
"#capacitor/filesystem": "^1.0.6",
"#capacitor/splash-screen": "latest",
"#ionic-native/core": "^5.36.0",
"#ionic-native/emm-app-config": "^5.36.0",
"cordova-plugin-emm-app-config": "^1.0.2",
"rxjs": "^7.4.0"
},
"devDependencies": {
"#capacitor/cli": "latest",
"webpack-cli": "^4.9.1"
},
"author": "",
"license": "ISC"
}
What am i missing?

My Strapi admin panel is now showing loading status indefinitely on localhost

This was not the case a few days ago, yesterday this randomly occurred after some changes were made as I had added a significant number of new Fields attributes to a specific Collection Type...
Ever since, my Strapi CMS NodeJS backend is randomly not loading anymore on my localhost, it shows an infinite loading status...
When I first go to my localhost:1337 this is what I get, it all works as it has been and has loaded properly:
However, when I click "Open the administration" button to access the Strapi admin panel I get directed to "http://localhost/admin" and get the following:
When I click on the admin error in the Network tab, it shows the following:
Normally, the "Open the administration" tab would redirect me to http://localhost:1337/admin however clearly this time it did not.
Now I try to access http://localhost:1337/admin and this is where I receive the seemingly infinite loading error...
The first (failed) fetch error (above the preflight error, as this is causing the preflight error), shows:
My server.js file is as follows:
module.exports = ({ env }) => ({
host: env('HOST', '0.0.0.0'),
port: env.int('PORT', 1337),
cron: { enabled: true },
url: env('URL', 'http://localhost'),
admin: {
auth: {
secret: env('ADMIN_JWT_SECRET', '9bf8cc74ab83590b280df0851beaec60'),
},
},
});
My package.json is as follows:
{
"name": "Strapi-Backend",
"private": true,
"version": "0.1.0",
"description": "The Strapi backend of a JAMstack e-commerce platform built for a Udemy course.",
"scripts": {
"develop": "strapi develop",
"start": "strapi start",
"build": "strapi build",
"strapi": "strapi"
},
"devDependencies": {},
"dependencies": {
"strapi": "3.6.8",
"strapi-admin": "3.6.8",
"strapi-connector-mongoose": "3.6.8",
"strapi-plugin-content-manager": "3.6.8",
"strapi-plugin-content-type-builder": "3.6.8",
"strapi-plugin-email": "3.6.8",
"strapi-plugin-graphql": "^3.6.8",
"strapi-plugin-upload": "3.6.8",
"strapi-plugin-users-permissions": "3.6.8",
"strapi-provider-email-sendgrid": "^3.6.8",
"strapi-provider-upload-aws-s3": "^3.6.8",
"strapi-utils": "3.6.8",
"stripe": "^8.135.0"
},
"author": {
"name": "Zachary Reece"
},
"strapi": {
"uuid": "5e0b8d89-62ac-4e4e-995b-08644071605b"
},
"engines": {
"node": ">=10.0.0",
"npm": ">=6.0.0"
},
"license": "MIT"
}
Change server.js and try:
module.exports = ({ env }) => {
const port = env('PORT', '1337');
const host = env('HOST', '0.0.0.0');
const url = env('URL', `http://localhost${port !== '80' ? ':'+port : ''}`);
const adminAuthSecret = env('ADMIN_JWT_SECRET', '9bf8cc74ab83590b280df0851beaec60');
return {
host, port, url,
cron: { enabled: true },
cors: { enabled: true, origin: ['*'] },
admin: {
auth: { secret: adminAuthSecret },
}
}
};

Push notifications when the Electron app is turned off

My electron app is using the remote isolation approach (mentioned in this article). My remote web app is a Ruby on Rails app. Now, I want to push notifications from a remote web app to the electron app using WebSocket. To send the message to users even if they shut off the app, I got an idea. In the Rails server, I use ActionCable to broadcast the notifications to a channel. In the main process, I subscribe to this channel by using the actioncable package.
import ActionCable from "actioncable";
const websocketUrl = "wss://rt.custom-domain.dev/_/cable";
const cable = ActionCable.createConsumer(websocketUrl);
cable.subscriptions.create(
{ channel: "WallChannel", wall_id: "106" },
{
received(data: any): void {},
disconnect(): void {},
connected(): void {},
disconnected(): void {},
present(): void {},
absent(): void {},
}
);
But I got an error:
ReferenceError: window is not defined
Then I dive deep into the source code of the actioncable package and I found that the package using WebSocket API of the browser so that why the error appeared.
I tried to use ws package to subscribe to the websocket instead by following this post. But I couldn't connect to the websocket server. When I call App.ws.sendmessage I got an error:
Error: WebSocket is not open: readyState 0 (CONNECTING)
Has anyone tried to push notifications from the remote web app by using websocket like what I've trying? Did you got the same problem? or If you got a better solution for my case, please share with me your idea. Thanks a lot.
This is my main.ts file of the electron app
import { app, BrowserWindow, ipcMain, Notification } from "electron";
import { createWindow } from "src/main/CreateWindow";
import { showNotification } from "./helpers";
import appConfigs from "src/AppConfigs";
let mainWindow: BrowserWindow;
const createAppWindow = () => {
mainWindow = createWindow(appConfigs.targetUrl, { interop: true });
// Open the DevTools.
if (!app.isPackaged) {
mainWindow.webContents.openDevTools();
}
};
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require("electron-squirrel-startup")) {
// eslint-disable-line global-require
app.quit();
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", () => {
createAppWindow();
});
var App: { ws: any; param: any; connect_server: any; sendmessage: any } = {
ws: null,
param: null,
connect_server: () => {},
sendmessage: () => {},
};
App.sendmessage = function (send: any) {
let data = {
message: send,
action: "speak",
};
let message = {
command: "message",
identifier: JSON.stringify(App.param),
data: JSON.stringify(data),
};
App.ws.send(JSON.stringify(message));
};
App.connect_server = function () {
const WebSocket = require("ws");
App.ws = new WebSocket("wss://rt.custom-domain.dev/_/cable", [
"actioncable-v1-json",
"actioncable-unsupported",
]);
console.log("connect_server", App.ws);
App.param = { channel: "WallChannel", wall_id: 106 };
App.ws.on("open", function open() {
console.log("open channel");
let data = {
command: "subscribe",
identifier: JSON.stringify(App.param),
};
App.ws.send(JSON.stringify(data));
console.log("send JSON");
});
App.ws.on("message", function (event: any) {
console.log("message", event);
});
App.ws.on("error", function (err) {
console.log("Found error: " + err);
});
};
App.connect_server();
CreateWindow.ts
import { BrowserWindow } from "electron";
import appConfigs from "src/AppConfigs";
declare const MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY: any;
interface BrowserWindowOption {
title?: string;
height?: string;
width?: string;
interop?: boolean;
}
export const createWindow = (
url: string,
options: BrowserWindowOption = {}
): BrowserWindow => {
// Create the browser window.
const mainWindow = new BrowserWindow({
title: options.title || appConfigs.name,
height: options.height || appConfigs.height,
width: options.width || appConfigs.width,
webPreferences: options.interop
? {
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
}
: {},
});
// and load the targetUrl.
mainWindow.loadURL(url || appConfigs.targetUrl);
return mainWindow;
};
package.json
{
"name": "electron-forge-app",
"productName": "electron-forge-app",
"version": "1",
"description": "My Electron application description",
"main": ".webpack/main",
"scripts": {
"start": "electron-forge start",
"package": "electron-forge package",
"make": "electron-forge make",
"publish": "electron-forge publish",
"lint": "eslint --ext .ts ."
},
"keywords": [],
"author": {
...
},
"license": "MIT",
"config": {
"forge": {
"packagerConfig": {},
"makers": [
{
"name": "#electron-forge/maker-squirrel",
"config": {
"name": "electron_furge"
}
},
{
"name": "#electron-forge/maker-zip",
"platforms": [
"darwin"
]
},
{
"name": "#electron-forge/maker-deb",
"config": {}
},
{
"name": "#electron-forge/maker-rpm",
"config": {}
}
],
"plugins": [
[
"#electron-forge/plugin-webpack",
{
"mainConfig": "./webpack.main.config.js",
"renderer": {
"config": "./webpack.renderer.config.js",
"entryPoints": [
{
"html": "./src/index.html",
"js": "./src/renderer.ts",
"name": "main_window",
"preload": {
"js": "./src/interop/preload.ts"
}
}
]
}
}
]
]
}
},
"devDependencies": {
"#electron-forge/cli": "^6.0.0-beta.54",
"#electron-forge/maker-deb": "^6.0.0-beta.54",
"#electron-forge/maker-rpm": "^6.0.0-beta.54",
"#electron-forge/maker-squirrel": "^6.0.0-beta.54",
"#electron-forge/maker-zip": "^6.0.0-beta.54",
"#electron-forge/plugin-webpack": "6.0.0-beta.54",
"#marshallofsound/webpack-asset-relocator-loader": "^0.5.0",
"#types/actioncable": "^5.2.4",
"#typescript-eslint/eslint-plugin": "^4.0.1",
"#typescript-eslint/parser": "^4.0.1",
"css-loader": "^4.2.1",
"electron": "12.0.5",
"eslint": "^7.6.0",
"eslint-plugin-import": "^2.20.0",
"fork-ts-checker-webpack-plugin": "^5.0.14",
"node-loader": "^1.0.1",
"style-loader": "^1.2.1",
"ts-loader": "^8.0.2",
"typescript": "^4.0.2"
},
"dependencies": {
"actioncable": "^5.2.6",
"electron-squirrel-startup": "^1.0.0",
"ws": "^7.4.5"
}
}

Cannot get response from getStateByPartialCompositeKey

I cannot obtain a response from the getStateByPartialCompositeKey method. I can use putState and getState just fine, but cannot use getStateByPartialCompositeKey. I'm using NodeJS fabric-contract-api version of Fabric's chaincode.
For the development, I used this commercial-paper example. This example uses the test-network environment, which is working just fine.
This implementation offers some ledger API utility classes that I'm using also to interact with the ledger. It has two classes, state.js and stateList.js I added a method to stateliest called getAllStatesFromPartialCompositeKey to try and use getStateByPartialCompositeKey method.
Package.json
{
"name": "informed-consent-form-contract",
"version": "0.0.5",
"description": "Papernet Contract",
"main": "index.js",
"engines": {
"node": ">=8",
"npm": ">=5"
},
"scripts": {
"lint": "eslint .",
"pretest": "npm run lint",
"test": "nyc mocha test --recursive",
"start": "fabric-chaincode-node start",
"mocha": "mocha test --recursive"
},
"engineStrict": true,
"author": "hyperledger",
"license": "Apache-2.0",
"dependencies": {
"axios": "^0.19.2",
"fabric-contract-api": "^2.0.0",
"fabric-shim": "^2.0.0",
"node-fetch": "^2.6.0",
"nodemon": "^2.0.2"
},
"devDependencies": {
"chai": "^4.1.2",
"chai-as-promised": "^7.1.1",
"eslint": "^4.19.1",
"mocha": "^5.2.0",
"nyc": "^12.0.2",
"sinon": "^6.0.0",
"sinon-chai": "^3.2.0"
},
"nyc": {
"exclude": [
"coverage/**",
"test/**"
],
"reporter": [
"text-summary",
"html"
],
"all": true,
"check-coverage": true,
"statements": 100,
"branches": 100,
"functions": 100,
"lines": 100
}
}
Contract.js snippet:
/**
*
* #param {*} ctx
* #param {*} partialKey - Piece of key to serch
*/
async getAllStates(ctx, partialKey) {
let result = await ctx.informedConsentFormStateList.getStatesFromPartialCompositeKey(partialKey);
console.log('================ Result inside getAllStates method ================');
console.log(result);
return result;
} // fin func
Insinde informedConsentFormStateList.js:
```
async getStatesFromPartialCompositeKey(partialKey) {
return this.getAllStatesFromPartialCompositeKey(partialKey);
}
```
Inside the modified stateList.js:
/**
* #function getAllStatesFromPartialCompositeKey
*/
async getAllStatesFromPartialCompositeKey(partialArgument) {
console.log('================ Called from beginning of getAllStatesFromPartialCompositeKey ================');
console.log('================ name => ' + this.name);
let key = this.ctx.stub.createCompositeKey(this.name, [partialArgument]);
console.log('================ created partial key .....');
console.log(partialArgument);
console.log(key);
let response = await this.ctx.stub.getStateByPartialCompositeKey(this.name, [key]); //.toString('utf8')
console.log('================ response below ================');
console.log(response);
let results = await this.getAllResults(response);
return results;
} // fin getAllStatesFromPartialCompositeKey
Here is how I invoke it:
/home/ubilab/fabric2/fabric-samples/test-network$ peer chaincode invoke -o localhost:7050 --ordererTLSHostnameOverride orderer.example.com --channelID mychannel --name informed_consent_9 --tls true --cafile $ORDERER_CA --peerAddresses localhost:7051 --tlsRootCertFiles $ORG1_CA -c '{"Args":["csacmpcc:getAllStates","P03"]}'
Response:
chaincodeInvokeOrQuery -> INFO 001 Chaincode invoke successful. result: status:200 payload:"[]"
Chaincode container logs:
================ Called from beginning of getAllStatesFromPartialCompositeKey ================
================ name => org.csa.informedconsentformstatelist
================ created partial key .....
P03
org.csa.informedconsentformstatelistP03
================ Result inside getAllStates method ================
[]
Couchdb Stored state:
{
"id": "\u0000org.csa.informedconsentformstatelist\u0000\"P03\"\u0000\"R68\"\u0000",
"key": "\u0000org.csa.informedconsentformstatelist\u0000\"P03\"\u0000\"R68\"\u0000",
"value": {
"rev": "1-74db76a10ad8251ce2ba49ad58710ad8"
},
"doc": {
"_id": "\u0000org.csa.informedconsentformstatelist\u0000\"P03\"\u0000\"R68\"\u0000",
"_rev": "1-74db76a10ad8251ce2ba49ad58710ad8",
"class": "org.csa.informedconsentform",
"consentStatus": "1",
"currentState": null,
"key": "\"P03\":\"R68\"",
"patientID": "P03",
"reserachID": "R68",
"sensors": "{numberOfSensors:1,sensors:[{sensorID:s01,name:SPO2,startDate:5/12/2020,endDate:5/12/2021}]}",
"~version": "CgMBZQA="
}
}
If you need more information to be able to help me please do not hesitate to ask :). Thanks!
Given you are querying with a single attribute, try using the partialKey variable directly instead of building a composite key.
let response = await this.ctx.stub.getStateByPartialCompositeKey(this.name, [partialKey]);
API docs
A better way to get a response would be to use an iterator :
let allResults = [];
let res = { done: false, value: null };
let jsonRes = {};
res= await ctx.stub.getStateByPartialCompositeKey(this.name, [partialKey]);
while (!res.done) {
jsonRes.Key = res.value.key;
try {
jsonRes.Record = JSON.parse(res.value.value.toString('utf8'));
allResults.push(jsonRes);
res = await iterator.next();
}
catch (err) {
console.log(err);
return {}
}
}
await iterator.close();
return allResults;

Giving TypeError: client.findElement is not a function. when trying to locate android app element through javascript and mocha

I am trying to locate the element using Javascript, appium, WebdriverIo and Mocha. The app is getting launch on emulator but getting error while locating element.Any other approach that can be used?
The testclass.js file code is given below:
const wdio = require("webdriverio");
//example capabilities
const opts = {
port: 4723,
capabilities: {
platformName: "Android",
deviceName: "emulator-5554",
app: "D:demo.apk",
appPackage: "com.somepackage",
appActivity: "com.somepackage.acivity",
newCommandTimeout: 500,
noReset: "true",
automationName: "UiAutomator2"
}
};
var client = wdio.remote(opts);
describe('Test App launch', function () {
this.timeout(15000);
it('register', async function(){
// This is the error line below
**const elm = await client.findElement("resource-id","goRegistrationButton")**
elm.click();
});
});
package.json file:
{
"name": "testclass",
"version": "1.0.0",
"description": "Automating app",
"main": "testclass.js",
"scripts": {
"test": "testclass.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"mocha": "^6.0.2",
"typescript": "^3.3.4000",
"webdriverio": "^5.7.6"
},
"devDependencies": {
"ts-node": "^8.0.3"
}
}
I am expecting to click the element for the native android app using javascript and webdriverIO

Categories