Domino 10 AppDevPack local installation problem - node.js

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.

Related

Cannot catch BadRequestException thrown by FilesInterceptor

I am trying to set up a logic to save uploaded files using Multer.
To do this, I follow the Nestjs tutorial and use the "FilesInterceptor" interceptor.
controller file :
import {
Controller,
FileValidator,
ParseFilePipe,
Post,
UploadedFiles,
UseInterceptors
} from '#nestjs/common';
import { FilesInterceptor } from '#nestjs/platform-express';
import { Public } from 'src/auth/decorators/public.decorator';
import { MimeTypeValidationPipe } from './pipes/mimetype.validation.pipe';
const ACCEPTED_FILE_MIMETYPES = ["image/jpeg", "image/jpg", "image/png"]
const validators: FileValidator[] = [
new MimeTypeValidationPipe({ accepted: ACCEPTED_FILE_MIMETYPES })
];
#Controller('uploads')
export class UploadsController {
#Public()
#Post("/")
#UseInterceptors(FilesInterceptor("files"))
public async create(
#UploadedFiles(new ParseFilePipe({ validators }))
files: Express.Multer.File[]
){
files[0].originalname
const filenames = files.map(({ originalname }) => originalname)
return { filenames };
}
}
However, when I test the behavior of the server when the number of uploaded files exceeds the limit, the server returns me an error 500 (As if the error was not handled).
I then try to catch it by using an ExcepetionFilter like this one:
#Catch()
class TestFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
console.debug(exception)
if(exception instanceof HttpException) console.debug("This is an HTTP Exception !");
else console.debug("This is NOT an HTTP Exception");
const response = host.switchToHttp().getResponse<Response>();
return response.status(500).json({statusCode: 500 , message: "ERROR" });
}
}
And i get the following output :
BadRequestException: Too many files
at transformException (~/development/Nest/nestapi/node_modules/#nestjs/platform-express/multer/multer/multer.utils.js:19:20)
at ~/development/Nest/nestapi/node_modules/#nestjs/platform-express/multer/interceptors/files.interceptor.js:18:73
at ~/development/Nest/nestapi/node_modules/#nestjs/platform-express/node_modules/multer/lib/make-middleware.js:53:37
at AsyncResource.runInAsyncScope (node:async_hooks:202:9)
at listener (~/development/Nest/nestapi/node_modules/#nestjs/platform-express/node_modules/on-finished/index.js:170:15)
at onFinish (~/development/Nest/nestapi/node_modules/#nestjs/platform-express/node_modules/on-finished/index.js:101:5)
at callback (~/development/Nest/nestapi/node_modules/#nestjs/platform-express/node_modules/ee-first/index.js:55:10)
at IncomingMessage.onevent (~/development/Nest/nestapi/node_modules/#nestjs/platform-express/node_modules/ee-first/index.js:93:5)
at IncomingMessage.emit (node:events:539:35)
at endReadableNT (node:internal/streams/readable:1345:12) {
response: { statusCode: 400, message: 'Too many files', error: 'Bad Request' },
status: 400
}
This is NOT an HTTP Exception
The filter indicates that it is NOT an HTTPException.
However, while digging in the FilesInterceptor.ts code I notice that the caught errors are handled by a small utility function "transformException" which is supposed to transform the Multer error into an HttpException (depending on the error code returned by Multer)
multer.utils.ts file (from nest repo)
import {
BadRequestException,
HttpException,
PayloadTooLargeException,
} from '#nestjs/common';
import { multerExceptions } from './multer.constants';
export function transformException(error: Error | undefined) {
if (!error || error instanceof HttpException) {
return error;
}
switch (error.message) {
case multerExceptions.LIMIT_FILE_SIZE:
return new PayloadTooLargeException(error.message);
case multerExceptions.LIMIT_FILE_COUNT:
case multerExceptions.LIMIT_FIELD_KEY:
case multerExceptions.LIMIT_FIELD_VALUE:
case multerExceptions.LIMIT_FIELD_COUNT:
case multerExceptions.LIMIT_UNEXPECTED_FILE:
case multerExceptions.LIMIT_PART_COUNT:
return new BadRequestException(error.message);
}
return error;
}
I don't understand why my filter (and NestJS' unhandledExceptionFilter) can't detect this exception, since for me it is supposed to be an instance of HttpException.
Can you help me?
Best regards
You probably have 2 copies of #nestjs/common being included in your project. The code that creates the error is using one copy, and your exception filter is using the other copy. When your code is checking instanceof, it's checking to see if the exception is an instance of HttpException from it's copy of #nestjs/common, but it's not, it's an instance of HttpException from the other copy of #nestjs/common. This is known as "multiple realms" (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof#instanceof_and_multiple_realms).
The way to fix this is to make sure you only have 1 copy of #nestjs/common in your project. Often, the reason you have 2 is because you have 2 package.json files with different version specs that they call for (e.g. "#nestjs/common": "^8.0.0" in one package.json, and "#nestjs/common": "^9.0.0" in another). You may need to use e.g. the overrides key to force a dependency to use the same version that you use elsewhere.
Hope that helps!
Sorry!
I think the problem is with me.
The LTS version (1.4.4-lts.1) of multer is buggy. So I decided to downgrade to 1.4.4 (version in which the bug in question does not occur). But to do so, I had to downgrade the nested dependency manually by doing npm install multer#1.4.4 in the node_modules/#nest/platform-express directory.
But that's when nestjs starts to format my errors badly.
The funny thing is that going back (npm install multer#1.4.4-lts.1 to the node_modules/#nest/platform-express directory), it doesn't solve the problem (Errors are still badly handled) and I have to delete the node_modules/#nest/platform-express folder and reinstall the package from the root of the project to get everything back in order (But with the LTS version bug, of course).
It's weird.

How can I use packages that extend `koa.Request` in TypeScript?

I am trying to use koa-tree-router and koa-bodyparser at the same time, but I keep getting TypeScript errors:
export const userLoggingRouter = new KoaTreeRouter<any, DefaultContext>();
userLoggingRouter.post('/logs/action', (ctx) => {
const logEntries = ctx.request.body;
const user = ctx.state.user;
// ...
});
error TS2339: Property 'body' does not exist on type 'Request'.
I have #types/koa-bodyparser installed, and it contains the following definition:
import * as Koa from 'koa';
declare module 'koa' {
interface Request {
body: string | Record<string, unknown>;
rawBody: string;
}
}
But it doesn't seem to do anything. I found this question, but importing koa-bodyparser directly also does not do anything. How do I get TypeScript to recognize the extended Request type?
Edit: Creating a .d.ts file inside my project containing the following:
import {Request} from "koa";
declare module "koa" {
interface Request {
body: any;
}
}
Made the compile error go away, but this seems like an inelegant solution because I would have to copy over type information for every package that modifies koa.Request.
This was happening because I was using Yarn PnP and I had two different versions of #types/koa installed. Once I added a resolutions field to my package.json that forced all of the other TypeScript definitions to use the same version of #types/koa, everything worked.

Error when connecting to SQL Server in deno: 'cannot find module crypto'

I'm trying to port a nodejs MS SQL Server application to deno. I'm using the node compatibility library to allow the use of npm mssql package:
import { createRequire } from "https://deno.land/std/node/module.ts";
const require = createRequire(import.meta.url);
const sql = require('mssql')
async () => {
try {
await sql.connect('mssql://user:pwd#host/database')
const result = await sql.query`select * from the_table`
console.dir(result)
} catch (err) {
console.log('Error:', err)
}
}
However I'm getting an error:
error: Uncaught Error: Cannot find module 'crypto' Require stack:
C:\WORK\LEARN\DENO\node_modules\tedious\lib\connection.js
C:\WORK\LEARN\DENO\node_modules\tedious\lib\tedious.js
C:\WORK\LEARN\DENO\node_modules\mssql\lib\tedious.js
Note: upgrading to the latest version of mssql helped, getting a different error, 'unable to find module tty', which I think I can figure out.
The crypto library internal to Node is used internally by the mssql library, however this isn't fully ported to Deno yet as you can see here
https://deno.land/std#0.83.0/node

Connection "default" was not found - TypeORM, NestJS and external NPM Package

I'm using NestJs to create a couple of applications and I want to move the code from a NestInterceptor for an external NPM Package so I can use the same interceptor in multiple applications.
The problem is that the same code that works when used "locally" just stop working when moved to the external package.
Here's the code for the interceptor:
import { Injectable, NestInterceptor, CallHandler, ExecutionContext } from '#nestjs/common'
import { map } from 'rxjs/operators'
import { getManager } from 'typeorm'
import jwt_decode from 'jwt-decode'
#Injectable()
export class MyInterceptor implements NestInterceptor {
entity: any
constructor(entity: any) {
this.entity = entity
}
async intercept(context: ExecutionContext, next: CallHandler): Promise<any> {
const request = context.switchToHttp().getRequest()
const repository = getManager().getRepository(this.entity)
return next.handle().pipe(map((data) => data))
}
}
Here's a given controller:
import { myInterceptor } from "../src/interceptors/interceptor.ts";
#UseInterceptors(new CompanyIdInterceptor(User))
export class UserController {
}
This works fine, but if a move the file to an external NPM package and import from it like this:
import { myInterceptor } from "mynpmpackage";
I get the following error:
[Nest] 24065 - 04/18/2019, 10:04 AM [ExceptionsHandler] Connection "default" was not found. +26114ms
ConnectionNotFoundError: Connection "default" was not found.
at new ConnectionNotFoundError (/home/andre/Services/npm-sdk/src/error/ConnectionNotFoundError.ts:8:9)
at ConnectionManager.get (/home/andre/Services/npm-sdk/src/connection/ConnectionManager.ts:40:19)
Any ideas, on what causes this and how to solve it?
This might not be your problem exactly, but I had a similar problem when moving things to external packages with TypeORM. Make sure all packages from parent project are using the same version of the TypeORM package.
In my case, using yarn why typeorm showed me two different versions were being installed. One of them was used to register the entities, while the framework connected to the SQL database using another version, generating this clash.
Check your versions using yarn why [pkg-name] or if you're using NPM, try npx npm-why [pkg-name] or install globally from https://www.npmjs.com/package/npm-why.
After verifying TypeOrm versions is same in both the packages i.e- external package and consumer repository as mentioned by #Luís Brito still issue persist then issue could be-
Basically when we create an external package - TypeORM tries to get the "default" connection option, but If not found then throws an error:
ConnectionNotFoundError: Connection "default" was not found.
We can solve this issue by doing some kind of sanity check before establishing a connection - luckily we have .has() method on getConnectionManager().
import { Connection, getConnectionManager, getConnectionOptions,
createConnection, getConnection, QueryRunner } from 'typeorm';
async init() {
let connection: Connection;
let queryRunner: QueryRunner;
if (!getConnectionManager().has('default')) {
const connectionOptions = await getConnectionOptions();
connection = await createConnection(connectionOptions);
} else {
connection = getConnection();
}
queryRunner = connection.createQueryRunner();
}
Above is a quick code-snippet which was the actual root cause for this issue but If you are interested to see complete working repositories (different example) -
External NPM Package :
Git Repo : git-unit-of-work (specific file- src/providers/typeorm/typeorm-uow.ts)
Published in NPM : npm-unit-of-work
Consumer of above package : nest-typeorm-postgre (specific files- package.json, src/countries/countries.service.ts & countries.module.ts)

How to use Hyperledger composer event subscriber in angular

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.

Resources