How to use Hyperledger composer event subscriber in angular - node.js

this is eventSubscrbie js File.
'use strict';
const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection;
class SubscribeEvent{
constructor() {
this.NetworkConnection = new BusinessNetworkConnection();
this.CONNECTION_PROFILE_NAME = "admin#resumenetwork";
}
init() {
return this.NetworkConnection.connect(this.CONNECTION_PROFILE_NAME)
.then((result) => {
this.businessNetworkDefinition = result;
//LOG.info(this.businessNetworkDefinition.getIdentifier());
})
// and catch any exceptions that are triggered
.catch(function (error) {
throw error;
});
}
/** Listen for the sale transaction events
*/
listen(){
this.NetworkConnection.on('event',(getEvent)=>{
var temp = JSON.stringify(getEvent['txForUser']);
var evt = JSON.parse(temp);
console.log(evt['certificateName']);
console.log(evt['certificateScore']);
console.log(evt['organizationId']);
console.log(evt['organizationName']);
console.log(evt['dob']);
console.log(evt['expirationDate']);
console.log(evt['isPublic']);
console.log(evt['userId']);
console.log(evt['timestamp']);
});
}
}
module.exports = SubscribeEvent;
I want to use the code in angular4 component.
so I insert a BusinessNetworkConnection module.
In component ts file,
import { BusinessNetworkConnection } from 'composer-client';
export class test {
var businessnetworkconnection = BusinessNetworkConnection();
}
as a result, warning message
WARNING in ./~/composer-common/lib/connectionprofilemanager.js
132:57-69 Critical dependency: the request of a dependency is an
expression
WARNING in ./~/composer-common/lib/log/logger.js 422:27-35 Critical
dependency: the request of a dependency is an expression
WARNING in ./~/composer-common/lib/log/logger.js 618:23-39 Critical
dependency: the request of a dependency is an expression
WARNING in ./~/composer-common/lib/config/configmediator.js 44:27-35
Critical dependency: the request of a dependency is an expression
WARNING in ./~/composer-common/lib/module/loadModule.js 71:25-43
Critical dependency: the request of a dependency is an expression
and same warning message was displayed at my angular web page
all dependency module is already installed.

you can ignore them. This is simply warning about a dependency written as an expression (as it mentions). There are some solutions on the web if you don't want to see the warning messages in Angular.

Related

Determine dependency's greatest matching version that exists on an NPM server from a semver version

I'm writing a node script which helps pin dependencies.
How can I determine the greatest realized version of a package existing on an NPM server, from a semver version?
For example, we have a dependency "foo" which is specified in a package.json as ~1.2.3.
Out on NPM, there exists published version 1.2.5, which is the latest published version compatible with ~1.2.3.
I need to write a script that would take as input "foo" and ~1.2.3, then after a server query, return 1.2.5. Something like this:
await fetchRealizedVersion('foo', '~1.2.3'); // resolves to 1.2.5
I understand I could do something like yarn upgrade and then parse the lock file, but I am looking for a more direct way of accomplishing this.
Hopefully there is a package that boils this down to an API call, but I'm not finding anything after googling around.
"Hopefully there is a package that boils this down to an API call,"
Short Answer: Unfortunately no, there is not a package that currently exists as far as I know.
Edit: There is the get-latest-version package you may want to try:
Basic usage:
const getLatestVersion = require('get-latest-version')
getLatestVersion('some-other-module', {range: '^1.0.0'})
.then((version) => console.log(version)) // highest version matching ^1.0.0 range
.catch((err) => console.error(err))
Alternatively, consider utilizing/writing a custom node.js module to perform the following steps:
Either:
Shell out the npm view command to retrieve all versions that are available in the NPM registry for a given package: For instance:
npm view <pkg> versions --json
Or, directly make a https request to the public npm registry at https://registry.npmjs.org to retrieve all versions available in for a given package.
Parse the JSON returned and pass it, along with the semver range (e.g. ~1.2.3), to the node-semver package's maxSatisfying() method.
The maxSatisfying() method is described in the docs as:
maxSatisfying(versions, range): Return the highest version in the list that satisfies the range, or null if none of them do.
Custom module (A):
The custom example module provided in get-latest-version.js (below) essentially performs the aforementioned steps. In this example we shell out the npm view command.
get-latest-version.js
'use strict';
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const { exec } = require('child_process');
const { maxSatisfying } = require('semver');
//------------------------------------------------------------------------------
// Data
//------------------------------------------------------------------------------
const errorBadge = '\x1b[31;40mERR!\x1b[0m';
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Captures the data written to stdout from a given shell command.
*
* #param {String} command The shell command to execute.
* #return {Promise<string>} A Promise object whose fulfillment value holds the
* data written to stdout. When rejected an error message is returned.
* #private
*/
function shellExec(command) {
return new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) {
reject(new Error(`Failed executing command: '${command}'`));
return;
}
resolve(stdout.trim());
});
});
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = {
/**
* Retrieves the latest version that matches the given range for a package.
*
* #async
* #param {String} pkg The package name.
* #param {String} range The semver range.
* #returns {Promise<string>} A Promise object that when fulfilled returns the
* latest version that matches. When rejected an error message is returned.
*/
async fetchRealizedVersion(pkg, range) {
try {
const response = await shellExec(`npm view ${pkg} versions --json`);
const versions = JSON.parse(response);
return maxSatisfying(versions, range);
} catch ({ message: errorMssg }) {
throw Error([
`${errorBadge} ${errorMssg}`,
`${errorBadge} '${pkg}' is probably not in the npm registry.`
].join('\n'));
}
}
};
Usage:
The following index.js demonstrates using the aforementioned module.
index.js
'use strict';
const { fetchRealizedVersion } = require('./get-latest-version.js');
(async function() {
try {
const latest = await fetchRealizedVersion('eslint', '~5.15.0');
console.log(latest); // --> 5.15.3
} catch ({ message: errMssg }) {
console.error(errMssg);
}
})();
As you can see, in that example we obtain the latest published version for the eslint package that is compatible with the semver tilde range ~5.15.0.
The latest/maximum version that satisfies ~5.15.0 is printed to the console:
$ node ./index.js
5.15.3
Note: You can always double check the results using the online semver calculator which actually utilizes the node-semver package.
Another Usage Example:
The following index.js demonstrates using the aforementioned module to obtain the latest/maximum version for multiple packages and different ranges.
index.js
'use strict';
const { fetchRealizedVersion } = require('./get-latest-version.js');
const criteria = [
{
pkg: 'eslint',
range: '^4.9.0'
},
{
pkg: 'eslint',
range: '~5.0.0'
},
{
pkg: 'lighthouse',
range: '~1.0.0'
},
{
pkg: 'lighthouse',
range: '^1.0.4'
},
{
pkg: 'yarn',
range: '~1.3.0'
},
{
pkg: 'yarn',
range: '^1.3.0'
},
{
pkg: 'yarn',
range: '^20.3.0'
},
{
pkg: 'quuxbarfoo',
range: '~1.3.0'
}
];
(async function () {
// Each request is sent and read in parallel.
const promises = criteria.map(async ({ pkg, range }) => {
try {
return await fetchRealizedVersion(pkg, range);
} catch ({ message: errMssg }) {
return errMssg;
}
});
// Log each 'latest' semver in sequence.
for (const latest of promises) {
console.log(await latest);
}
})();
The result for that last example is as follows:
$ node ./index.js
4.19.1
5.0.1
1.0.6
1.6.5
1.3.2
1.22.4
null
ERR! Failed executing command: 'npm view quuxbarfoo versions --json'
ERR! 'quuxbarfoo' is probably not in the npm registry.
Additional Note: The shellExec helper function in get-latest-version.js currently promisifies the child_process module's exec() method to shell out the npm view command. However, since node.js version 12 the built-in util.promisify provides another way to promisify the exec() method (as shown in the docs for exec), so you may prefer to do it that way instead.
Custom module (B):
If you wanted to avoid shelling out the npm view command you could consider making a request directly to the https://registry.npmjs.org endpoint instead (which is the same endpoint that the npm view command sends a https GET request to).
The modified version of get-latest-version.js (below) essentially utilizes a promisified version of the builtin https.get.
Usage is the same as demonstrated previously in the "Usage" section.
get-latest-version.js
'use strict';
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const https = require('https');
const { maxSatisfying } = require('semver');
//------------------------------------------------------------------------------
// Data
//------------------------------------------------------------------------------
const endPoint = 'https://registry.npmjs.org';
const errorBadge = '\x1b[31;40mERR!\x1b[0m';
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Requests JSON for a given package from the npm registry.
*
* #param {String} pkg The package name.
* #return {Promise<json>} A Promise object that when fulfilled returns the JSON
* metadata for the specific package. When rejected an error message is returned.
* #private
*/
function fetchPackageInfo(pkg) {
return new Promise((resolve, reject) => {
https.get(`${endPoint}/${pkg}/`, response => {
const { statusCode, headers: { 'content-type': contentType } } = response;
if (statusCode !== 200) {
reject(new Error(`Request to ${endPoint} failed. ${statusCode}`));
return;
}
if (!/^application\/json/.test(contentType)) {
reject(new Error(`Expected application/json but received ${contentType}`));
return;
}
let data = '';
response.on('data', chunk => {
data += chunk;
});
response.on('end', () => {
resolve(data);
});
}).on('error', error => {
reject(new Error(`Cannot find ${endPoint}`));
});
});
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = {
/**
* Retrieves the latest version that matches the given range for a package.
*
* #async
* #param {String} pkg The package name.
* #param {String} range The semver range.
* #returns {Promise<string>} A Promise object that when fulfilled returns the
* latest version that matches. When rejected an error message is returned.
*/
async fetchRealizedVersion(pkg, range) {
try {
const response = await fetchPackageInfo(pkg);
const { versions: allVersionInfo } = JSON.parse(response);
// The response includes all metadata for all versions of a package.
// Let's create an Array holding just the `version` info.
const versions = [];
Object.keys(allVersionInfo).forEach(key => {
versions.push(allVersionInfo[key].version)
});
return maxSatisfying(versions, range);
} catch ({ message: errorMssg }) {
throw Error([
`${errorBadge} ${errorMssg}`,
`${errorBadge} '${pkg}' is probably not in the npm registry.`
].join('\n'));
}
}
};
Note The version of node-semver used in the example custom modules (A & B) IS NOT the current latest version (i.e. 7.3.2). Version ^5.7.1 was used instead - which is the same version used by the npm cli tool.

ReferenceError: Cannot access 'web3' before initialization

chrome-browser-output
chrome-console
After installing the create-react-app package and then creating the web3.js file and adding the console.log(web3.version) to the App.js file im getting the above error and im not sure how to fix it and to get it working.
Ive also tried the following and it still throws the same error.
window.addEventListener('load', async () => {
// Modern dapp browsers...
if (window.ethereum) {
window.web3 = new Web3(ethereum);
try {
// Request account access if needed
await ethereum.enable();
// Acccounts now exposed
web3.eth.sendTransaction({/* ... */});
} catch (error) {
// User denied account access...
}
}
// Legacy dapp browsers...
else if (window.web3) {
window.web3 = new Web3(web3.currentProvider);
// Acccounts always exposed
web3.eth.sendTransaction({/* ... */});
}
// Non-dapp browsers...
else {
console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
}
});
Error can happen if you haven't called window.ethereum.enable(); yet.

Domino 10 AppDevPack local installation problem

I am at this the third day now, but can't find the way to successfully use the AppDevPack on my local angular app. I am working on a Mac, I have Angular v 8.15.0. I was able to successfully install the library but when ever I wan't to compile it, it breaks.
To describe: I've done almost everything to the script. The only difference is that I have made a service in which the #domino lives(it is not directly on a component).
The main problem seems to be with grpc and then with stream.
import { Injectable } from '#angular/core';
//import { useServer } from '#domino/domino-db/';
import * as useServer from '../../../node_modules/#domino/domino-db';
#Injectable({
providedIn: 'root'
})
export class DominoService {
private serverConfig = {
hostName: 'http://www.hostname.com/',
connection: { port:'3002'}
};
private databaseConfig = {
filePath: 'dev-tmp.nsf'
};
public database: any;
constructor() {
useServer( this.serverConfig ).then( async server => {
this.database = await server.useDatabase( this.databaseConfig );
});
const coll = this.database.bulkReadDocuments({
query: "Form = 'Document'"
});
console.log("Returned docs:" + JSON.stringify(coll));
}
Here are some of the errors:
Critical dependency: the request of a dependency is an expression
WARNING in
./node_modules/#domino/domino-db/node_modules/grpc/node_modules/node-pre-gyp/lib/pre-binding.js
20:22-48 Critical dependency: the request of a dependency is an
expression
WARNING in
./node_modules/#domino/domino-db/node_modules/grpc/node_modules/node-pre-gyp/lib/util/versioning.js 17:20-67 Critical dependency: the request of a dependency is an
expression
WARNING in
./node_modules/#domino/domino-db/node_modules/grpc/node_modules/minimatch/minimatch.js
Module not found: Error: Can't resolve 'path' in
'/Users/…/node_modules/#domino/domino-db/node_modules/grpc/node_modules/minimatch'
ERROR in
./node_modules/#domino/domino-db/node_modules/grpc/node_modules/detect-libc/lib/detect-libc.js
Module not found: Error: Can't resolve 'child_process' in
‘/…/node_modules/#domino/domino-db/node_modules/grpc/node_modules/detect-libc/lib'
Error: Can't resolve 'path' in
'/Users/.../node_modules/#domino/domino-db/node_modules/grpc/node_modules/minimatch'
ERROR in
./node_modules/#domino/domino-db/node_modules/grpc/node_modules/detect-libc/lib/detect-libc.js
Module not found: Error: Can't resolve 'child_process' in
'/Users/.../node_modules/#domino/domino-db/node_modules/grpc/node_modules/detect-libc/lib'
ERROR in
./node_modules/#domino/domino-db/node_modules/grpc/src/client.js
Module not found: Error: Can't resolve 'stream' in
'/Users/.../node_modules/#domino/domino-db/node_modules/grpc/src'
Critical dependency: the request of a dependency is an expression
From the error message, I can see that you're trying to webpack this. We do not support running domino-db on a webpage. Even if you got past this error, domino-db would fail to load in that environment because it's insecure.
Domino-db in production, secure environments requires client credentials to log in. Those aren't things you want to appear in the browser page.

How to use gulp-load-plugins with TypeScript?

I found no examples for gulp-load-plugins in TypeScript. Unfortunately,
my TypeScript is too poor to understand, what should to do from #type/gulp-load-plugins
comments.
I tried:
import * as _gulpPlugins from 'gulp-load-plugins';
const gulpPlugins: IGulpPlugins = _gulpPlugins();
return gulp.src(sourceFilesGlobSelections)
.pipe(gulpPlugins.pug())
// ...
It makes 4 warnings from Webpack (I dont understand where number such 75:13-25 refers; .pipe(gulpPlugins.pug()) is on 50 row):
WARNING in ../node_modules/gulp-load-plugins/index.js 75:13-25
Critical dependency: the request of a dependency is an expression
# ./TaskManagers/MarkupPreprocessingHelper.ts
WARNING in ../node_modules/gulp-load-plugins/index.js 81:48-63
Critical dependency: the request of a dependency is an expression
# ./TaskManagers/MarkupPreprocessingHelper.ts
WARNING in ../node_modules/gulp-load-plugins/index.js 117:40-55
Critical dependency: the request of a dependency is an expression
# ./TaskManagers/MarkupPreprocessingHelper.ts
WARNING in ../node_modules/gulp-load-plugins/index.js 122:51-66
Critical dependency: the request of a dependency is an expression
# ./TaskManagers/MarkupPreprocessingHelper.ts
It was told in #types/gulp-load-plugins:
/**
* Extend this interface to use Gulp plugins in your gulpfile.js
*/
interface IGulpPlugins {
}
I tried:
interface IGulpPlugins {
pug: () => NodeJS.ReadWriteStream;
}
It also defined:
declare module 'gulp-load-plugins' {
interface IOptions {
// ...
}
interface IPluginNameMappings {
[npmPackageName: string]: string
}
/** Loads in any gulp plugins and attaches them to an object, freeing you up from having to manually require each gulp plugin. */
function gulpLoadPlugins<T extends IGulpPlugins>(options?: IOptions): T;
// ...
}
It looks like maybe I should use gulpLoadPlugins instead of interface extending ...
Is is all that I understand with my current TypeScirpt proficiency, but it not enough to understand how to use gulp-load-plugins in TypeScript.
There is the working example in gulp-load-plugins-tests.ts:
import * as gulp from 'gulp';
import gulpConcat = require('gulp-concat');
import gulpLoadPlugins = require('gulp-load-plugins');
interface GulpPlugins extends IGulpPlugins {
concat: typeof gulpConcat;
}
gulp.task('taskName', () => {
gulp.src('*.*')
.pipe(plugins.concat('concatenated.js'))
.pipe(gulp.dest('output'));
});
About Critical dependency: the request of a dependency is an expression: do not bundle Node.js dependencies for the webpack projects those target is Node.js (not browser). webpack-node-externals will tell webpack do not bundle Node.js libraries, however it's still possible to import and use them as usual.

Is there a jest config that will fail tests on console.warn?

How do I configure jest tests to fail on warnings?
console.warn('stuff');
// fail test
You can use this simple override :
let error = console.error
console.error = function (message) {
error.apply(console, arguments) // keep default behaviour
throw (message instanceof Error ? message : new Error(message))
}
You can make it available across all tests using Jest setupFiles.
In package.json :
"jest": {
"setupFiles": [
"./tests/jest.overrides.js"
]
}
Then put the snippet into jest.overrides.js
For those using create-react-app, not wanting to run npm run eject, you can add the following code to ./src/setupTests.js:
global.console.warn = (message) => {
throw message
}
global.console.error = (message) => {
throw message
}
Now, jest will fail when messages are passed to console.warn or console.error.
create-react-app Docs - Initializing Test Environment
I implemented this recently using jest.spyOn introduced in v19.0.0 to mock the warn method of console (which is accesses via the global context / object).
Can then expect that the mocked warn was not called, as shown below.
describe('A function that does something', () => {
it('Should not trigger a warning', () => {
var warn = jest.spyOn(global.console, 'warn');
// Do something that may trigger warning via `console.warn`
doSomething();
// ... i.e.
console.warn('stuff');
// Check that warn was not called (fail on warning)
expect(warn).not.toHaveBeenCalled();
// Cleanup
warn.mockReset();
warn.mockRestore();
});
});
There is a useful npm package that helps you to achieve that: jest-fail-on-console
It's easily configurable.
Install:
npm i -D jest-fail-on-console
Configure:
In a file used in the setupFilesAfterEnv option of Jest, add this code:
import failOnConsole from 'jest-fail-on-console'
failOnConsole()
// or with options:
failOnConsole({ shouldFailOnWarn: false })
I decided to post a full example based on user1823021 answer
describe('#perform', () => {
var api
// the global.fetch is set to jest.fn() object globally
global.fetch = jest.fn()
var warn = jest.spyOn(global.console, 'warn');
beforeEach(function() {
// before every test, all mocks need to be resetted
api = new Api()
global.fetch.mockReset()
warn.mockReset()
});
it('triggers an console.warn if fetch fails', function() {
// In this test fetch mock throws an error
global.fetch.mockImplementationOnce(() => {
throw 'error triggered'
})
// I run the test
api.perform()
// I verify that the warn spy has been triggered
expect(warn).toHaveBeenCalledTimes(1);
expect(warn).toBeCalledWith("api call failed with error: ", "error triggered")
});
it('calls fetch function', function() {
// I create 2 more mock objects to verify the fetch parameters
const url = jest.fn()
const config = jest.fn()
api.url = url
api.config = config
// I run the test
api.perform()
// I verify that fetch has been called with url and config mocks
expect(global.fetch).toHaveBeenCalledTimes(1)
expect(global.fetch).toBeCalledWith(url, config)
expect(warn).toHaveBeenCalledTimes(0)
});
})
the #perform method I am testing
class Api {
constructor(auth) {
this._credentials = auth
}
perform = async () => {
try {
return await fetch(this.url, this.config)
} catch(error) {
console.warn('api call failed with error: ', error)
}
}
}
You can set the environment variable CI=true before running jest which will cause it to fail tests on warnings in addition to errors.
Example which runs all test files in the test folder:
CI=true jest ./test
Automated CI/CD pipelines such as Github Actions set CI to true by default, which can be one reason why a unit test will pass on your local machine when warnings are thrown, but fail in the pipeline.
(Here is the Github Actions documentation on default environment variables: https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables)

Resources