Cannot get response from getStateByPartialCompositeKey - javascript

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;

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?

redis port and host undefined even though env are set

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

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

Can not test something with mocha when I have angular (1.6) as a dependency

I want to test a ng-redux reducer wich have angular (1.6) as dependency.
When I run the tests (npm test) with mocha, I get :
/data/work/mocha-angularjs/node_modules/angular/angular.js:33343
})(window);
^
ReferenceError: window is not defined
I tried to add jsdom to provide a fake window. But it still fails during the import of angular with this error :
module.exports = angular;
^
ReferenceError: angular is not defined
Is there a way to make angular work properly in mocha/babel world ?
I made a small github project available here which reproduce the problem.
Here is the content of the project :
Package.json
{
"name": "mocha-angularjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"angular": "^1.6.3"
},
"devDependencies": {
"babel-core": "^6.24.0",
"babel-preset-es2015": "^6.24.0",
"babel-preset-latest": "^6.24.0",
"chai": "^3.5.0",
"jsdom": "9.12.0",
"jsdom-global": "2.1.1",
"mocha": "^3.2.0"
},
"scripts": {
"test": "NODE_ENV=test mocha src/index.test.js --compilers js:babel-register --require jsdom-global/register"
},
"repository": {
"type": "git",
"url": "git+https://github.com/jtassin/mocha-angularjs.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/jtassin/mocha-angularjs/issues"
},
"homepage": "https://github.com/jtassin/mocha-angularjs#readme"
}
.babelrc
{
"plugins": [],
"presets": [
"latest",
]
}
The code to test
import angular from 'angular';
export default function getFive() {
return 5;
}
The test
import expect from 'chai';
import getFive from './index';
describe('desc', () => {
it('my test', () => {
expect(getFive()).to.equal(5);
});
});
In case of someone needs it one day :
I used angularcontext to solve the problem.
package.json
"devDependencies": {
"angularcontext": "0.0.23",
[...]
},
In my test file
/* eslint-env mocha */
/* eslint-disable import/no-extraneous-dependencies */
import angularcontext from 'angularcontext';
before((done) => {
const context = angularcontext.Context();
context.runFile('./node_modules/angular/angular.js', (result, error) => {
if (error) {
/* eslint-disable no-console */
console.error(error);
done(error);
} else {
global.angular = context.getAngular();
done();
}
});
});
/* eslint-disable import/prefer-default-export */
export const angular = global.angular;
The github project has been updated with it.

How would I find what process is called a node.js script?

I work primarily with asp.net/C#/SQL applications, but have been handed a node.js/MongoDB application that I need to support. The client lost the original developers and I'm trying to figure fix an issue they're having. Currently I'm trying to find a "process" that runs and checks/makes updates to the database every 60 seconds. I've found the script that does the checks/updates, but I don't know where it gets called from or how the variables passed to it are getting populated. Can someone help me find how this "process" works?
So there's a script called eoaBatch.js that reads and writes to the database. It appears to have an object called api passed to it. It's that api object that I need to know how it is populated; that seems to be the current problem. Here's part of the code for eoaBatch.js:
exports.task = {
name: 'eoaBatch',
description: 'End of Batch Processor',
queue: 'eoa',
plugins: [],
pluginOptions: [],
frequency: 60 * 1000, // 1 minute
run: function (api, params, next) {
var Auction = mongoose.model('auctions');
var eoaBatch = mongoose.model('eoaBatches');
var eoaProperty = mongoose.model('eoaProperties');
var eoaBid = mongoose.model('eoaBids');
var Property = mongoose.model('properties');
var SubAccounts = mongoose.model('subaccounts');
var eoaAuction = mongoose.model('eoaAuctions');
async.eachSeries(
api.batches,
function forEachBatch(batchInfo, callback) {
How do I find out what calls/starts/runs this script?
How can I find what is in the api object?
Edit:
Here's package.json. I replaced the project name with PROJ and removed any other identifying information:
{
"name": "PROJ-api",
"version": "1.8.0",
"description": "PROJ",
"keywords": [
"PROJ"
],
"homepage": "https://www.PROJ.com",
"bugs": {
"email": ""
},
"license": "UNLICENSED",
"author": "",
"contributors": [
],
"repository": "/PROJ-api",
"scripts": {
"start": "node ./node_modules/.bin/actionhero start",
"ci-test": "istanbul cover _mocha > test.tap && istanbul report clover",
"ci-lint": "eslint -f checkstyle . > checkstyle-result.xml; true"
},
"dependencies": {
"accounting": "^0.4.1",
"actionhero": "^12.3.0",
"async": "^1.5.0",
"dateformat": "^1.0.12",
"grunt": "^0.4.5",
"kerberos": "0.0.17",
"lodash": "^3.10.1",
"mandrill-api": "^1.0.45",
"mongoose": "^4.2.9",
"mongoose-datatable": "^1.0.6",
"node-uuid": "^1.4.7",
"redis": "^2.4.2",
"tv4": "^1.2.7",
"validator": "^4.3.0",
"ws": "^0.8.1"
},
"devDependencies": {
"babel-eslint": "^5.0.0-beta4",
"babel-preset-airbnb": "^1.0.1",
"eslint": "^1.10.3",
"eslint-config-airbnb": "^1.0.2",
"eslint-plugin-react": "^3.11.2",
"istanbul": "^0.4.1",
"mocha": "^2.3.4",
"should": "latest"
},
"engines": {
"node": ">=4.2.0"
},
"os": [
"darwin",
"linux"
],
"private": true
}
This is a background job for a job queue implemented for ActionHero
Your file creates tasks.
From the docs:
api: The actionhero api object
params: An array of parameters that
the task was enqueued with. This is whatever was passed as the second
argument to api.tasks.enqueue
next: A callback to call when the task
is done. This callback is of the type function(error, result).
Passing an error object will cause the job to be marked as a failure.
The result is currently not captured anywhere.

Categories