Error: A circular dependency has been detected (property key: "firstName") thrown by tx-mixer - node.js

I'm using this wonderful lib: https://www.npmjs.com/package/ts-mixer
The whole traceback looks as follows:
(node:22654) UnhandledPromiseRejectionWarning: Error: A circular dependency has been detected (property key: "firstName"). Please, make sure that each side of a bidirectional relationships are using lazy resolvers ("type: () => ClassType").
at SchemaObjectFactory.createNotBuiltInTypeReference (/Users/albert/Documents/projects/albert/rlx/node_modules/#nestjs/swagger/dist/services/schema-object-factory.js:212:19)
at SchemaObjectFactory.mergePropertyWithMetadata (/Users/albert/Documents/projects/albert/rlx/node_modules/#nestjs/swagger/dist/services/schema-object-factory.js:143:25)
at /Users/albert/Documents/projects/albert/rlx/node_modules/#nestjs/swagger/dist/services/schema-object-factory.js:79:35
at Array.map (<anonymous>)
at SchemaObjectFactory.extractPropertiesFromType (/Users/albert/Documents/projects/albert/rlx/node_modules/#nestjs/swagger/dist/services/schema-object-factory.js:78:52)
at SchemaObjectFactory.exploreModelSchema (/Users/albert/Documents/projects/albert/rlx/node_modules/#nestjs/swagger/dist/services/schema-object-factory.js:92:41)
at /Users/albert/Documents/projects/albert/rlx/node_modules/#nestjs/swagger/dist/services/schema-object-factory.js:33:36
at Array.map (<anonymous>)
at SchemaObjectFactory.createFromModel (/Users/albert/Documents/projects/albert/rlx/node_modules/#nestjs/swagger/dist/services/schema-object-factory.js:20:45)
at exploreApiParametersMetadata (/Users/albert/Documents/projects/albert/rlx/node_modules/#nestjs/swagger/dist/explorers/api-parameters.explorer.js:33:55)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:22654) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:22654) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
register-common-user.dto.ts
export class RegisterCommonUserDto {
#decorate(ApiProperty())
#decorate(IsNotEmpty())
#decorate(IsString())
firstName: string;
// #decorate(ApiProperty())
#decorate(IsNotEmpty())
#decorate(IsString())
lastName: string;
// #decorate(ApiProperty({enum: EUserRoleName}))
#decorate(IsNotEmpty())
#decorate(IsEnum(EUserRoleName))
roleName: EUserRoleName;
// #decorate(ApiProperty())
#decorate(IsNotEmpty())
#decorate(IsPhoneNumber())
phoneNumber: string;
// #decorate(ApiProperty())
#decorate(IsNotEmpty())
#decorate(IsEmail())
email: string;
}
register-user.dto.ts
export class RegisterUserDto extends Mixin(
RegisterFighterDto,
RegisterCommonUserDto,
RegisterLocationProviderDto,
) {}
The method:
#Post('register')
public async registerUser(#Body() registerUserDto: RegisterUserDto): Promise<any> {
// code
}
What might be causing the problem? It has surely something to do with the #ApiProperty decorator being wrapped in decorate, cos when I comment out that line, the error disappears. But in that case decorators don't get inherited and that's the whole point of using the ts-mixer lib.
EDIT:
Any ideas?
EDIT:
Are these libs incompatible or what?

Recently, I learning Nest also have the same problem when attempt to use Swagger. This is my whole traceback looks as follows:
Error: A circular dependency has been detected (property key: "user"). Please, make sure that each side of a bidirectional relationships are using lazy resolvers ("type: () => ClassType").
at SchemaObjectFactory.createNotBuiltInTypeReference (/Users/wujie/Code/realworld/nestjs-realworld-example-app/node_modules/#nestjs/swagger/dist/services/schema-object-factory.js:170:19)
at SchemaObjectFactory.createSchemaMetadata (/Users/wujie/Code/realworld/nestjs-realworld-example-app/node_modules/#nestjs/swagger/dist/services/schema-object-factory.js:277:25)
at SchemaObjectFactory.mergePropertyWithMetadata (/Users/wujie/Code/realworld/nestjs-realworld-example-app/node_modules/#nestjs/swagger/dist/services/schema-object-factory.js:122:21)
at /Users/wujie/Code/realworld/nestjs-realworld-example-app/node_modules/#nestjs/swagger/dist/services/schema-object-factory.js:79:35
at Array.map (<anonymous>)
at SchemaObjectFactory.extractPropertiesFromType (/Users/wujie/Code/realworld/nestjs-realworld-example-app/node_modules/#nestjs/swagger/dist/services/schema-object-factory.js:78:52)
at SchemaObjectFactory.exploreModelSchema (/Users/wujie/Code/realworld/nestjs-realworld-example-app/node_modules/#nestjs/swagger/dist/services/schema-object-factory.js:92:41)
at /Users/wujie/Code/realworld/nestjs-realworld-example-app/node_modules/#nestjs/swagger/dist/swagger-explorer.js:217:64
at Array.forEach (<anonymous>)
at SwaggerExplorer.registerExtraModels (/Users/wujie/Code/realworld/nestjs-realworld-example-app/node_modules/#nestjs/swagger/dist/swagger-explorer.js:217:21)
Analyze the error code information,I found the problem is the decorator ApiExtraModels(), and the code I wrote is:
import { applyDecorators, Type } from '#nestjs/common';
import { ApiOkResponse, ApiExtraModels, getSchemaPath } from '#nestjs/swagger';
import { ApiUserResDto, PaginatedDto } from './dto/api-res.dto';
/** 用户信息返回限定装饰器 */
export const ApiUserResponse = <TModel extends Type<any>>(model: TModel) => {
return applyDecorators(
ApiOkResponse({
schema: {
title: `UserResponseOf${model.name}`,
allOf: [
{ $ref: getSchemaPath(ApiUserResDto) },
{
properties: {
user: {
type: 'object',
$ref: getSchemaPath(model)
}
}
}
]
}
}),
ApiExtraModels(ApiUserResDto),
ApiExtraModels(model)
);
};`
and the apiUserResDto class is:
export class ApiUserResDto<Dto> {
user: Dto;
}
according to the cli tips, just change ApiExtraModels(ApiUserResDto) to ApiExtraModels(() => ApiUserResDto), should solve this problem.

Related

Nest server not connecting to MongoDB cloud UnhandledPromiseRejectionWarning: MongoParseError: URI malformed

My NestJS backend needs to connect to the mongodb cloud, I followed the docs from here
The following error threw up in the terminal:
(node:6920) UnhandledPromiseRejectionWarning: MongoParseError: URI malformed
at new ConnectionString (D:\growth\quizbackend\quizbackend\node_modules\mongodb-connection-string-url\src\index.ts:113:13)
at Object.parseOptions (D:\growth\quizbackend\quizbackend\node_modules\mongodb\src\connection_string.ts:249:15)
at new MongoClient (D:\growth\quizbackend\quizbackend\node_modules\mongodb\src\mongo_client.ts:332:22)
at D:\growth\quizbackend\quizbackend\node_modules\mongoose\lib\connection.js:785:16
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (D:\growth\quizbackend\quizbackend\node_modules\mongoose\lib\connection.js:782:19)
at Mongoose.createConnection (D:\growth\quizbackend\quizbackend\node_modules\mongoose\lib\index.js:275:10)
at Function.<anonymous> (D:\growth\quizbackend\quizbackend\node_modules\#nestjs\mongoose\dist\mongoose-core.module.js:60:63)
at Generator.next (<anonymous>)
at D:\growth\quizbackend\quizbackend\node_modules\#nestjs\mongoose\dist\mongoose-core.module.js:20:71
(Use `node --trace-warnings ...` to show where the warning was created)
(node:6920) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:6920) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future,
promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
My app module code:
import { Module } from '#nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersModule } from './users/users.module';
import {MongooseModule} from '#nestjs/mongoose'
#Module({
imports: [UsersModule,MongooseModule.forRoot('mongodb+srv://icfoajscijwq90j#cluster0.8rxa2.mongodb.net/nest-js-db?retryWrites=true&w=majority')],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
I doubled check my username and password but they are correct, is there any need for encoding them or why the error is throwing up any explanation would be appreciated.
Ensure that your username and password in the URI Connection string doesn't have any illegal characters.
If the username or password includes the following characters:
: / ? # [ ] #
those characters must be converted using percent encoding.
Based on their documentation: https://docs.mongodb.com/manual/reference/connection-string/

Nestjs Repository test fails with error "Received promise resolved instead of rejected"

I am writing unit tests for my backend application, I am struggling to test for a item in the database not being found, this is the code for my repository to be tested:
#EntityRepository(Collectible)
export class CollectibleRepository extends Repository<Collectible> {
async getCollectible(id: number) {
const collectible = await this.findOne(id);
if (!collectible) {
throw new NotFoundException();
}
return collectible;
}
}
And this is the code for testing, I will only show this test case.
const mockCollectible = new Collectible(
faker.lorem.sentence(),
faker.lorem.sentences(3),
faker.datatype.float(),
faker.datatype.float(),
faker.datatype.number(),
);
describe('Collectible Repository', () => {
let collectibleRepository: CollectibleRepository;
beforeEach(async () => {
const module = await Test.createTestingModule({
providers: [CollectibleRepository],
}).compile();
collectibleRepository = module.get<CollectibleRepository>(
CollectibleRepository,
);
});
describe('View Collectibles', () => {
it('throws and error as the collectible is not found', async (done) => {
collectibleRepository.findOne = jest.fn().mockResolvedValue(undefined);
await expect(collectibleRepository.getCollectible(1)).rejects.toThrow(
NotFoundException,
);
done();
});
});
});
This causes the following error output:
Expected message: not "Not Found"
8 | const collectible = await this.findOne(id, { relations: ['business'] });
9 | if (!collectible) {
> 10 | throw new NotFoundException();
| ^
11 | }
12 | return collectible;
13 | }
at CollectibleRepository.getCollectibleBusiness (src/collectible/collectible.repository.ts:10:13)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:95012) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:95012) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
FAIL src/collectible/collectible.repository.spec.ts (8.525 s)
● Collectible Repository › View Collectibles › throws and error as the collectible is not found
expect(received).rejects.not.toThrow()
Received promise resolved instead of rejected
Resolved to value: undefined
39 | it('throws and error as the collectible is not found', async (done) => {
40 | collectibleRepository.findOne = jest.fn().mockResolvedValue(undefined);
> 41 | await expect(collectibleRepository.getCollectible(1)).rejects.not.toThrow(
| ^
42 | NotFoundException,
43 | );
44 | done();
at expect (../node_modules/expect/build/index.js:134:15)
at Object.<anonymous> (collectible/collectible.repository.spec.ts:41:13)
I tried using this repository (which was mentioned in another SO thread) with a set of examples for testing Nest.js applications, but it seems like a repository is not being directly tested.
Update: I updated my code since I was missing a await in my code (as noted by Micael Levi ), I was also calling the wrong function (lol). I am receiving the following warning:
(node:98378) UnhandledPromiseRejectionWarning: Error: expect(received).rejects.not.toThrow(expected)
Though probably I will ignore it unless it affects my CI pipeline (which I need to configure lmao)
Update 2: Warning was caused by another test (I may rest for now).
you missed the await in const collectible = this.findOne(id);
So
const collectible = await this.findOne(id);

I'm trying to make an announcement command but getting an error

So basically I'm trying to send an announcement to specific channel using message.mentions.channels
ex !announce #announcements Today is a great day!
Error:
(node:5516) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'channels' of undefined
at Object.module.exports.execute (C:\Users\Zarko\Desktop\Stackoverflow\commands\Answers\announce.js:3:36)
at Client.<anonymous> (C:\Users\Zarko\Desktop\Stackoverflow\events\message.js:20:30)
at Client.emit (events.js:223:5)
at MessageCreateAction.handle (C:\Users\Zarko\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\Zarko\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\Zarko\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (C:\Users\Zarko\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (C:\Users\Zarko\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (C:\Users\Zarko\node_modules\discord.js\node_modules\ws\lib\event-target.js:125:16)
at WebSocket.emit (events.js:223:5)
(node:5516) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:5516) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Code:
let channel = message.mentions.channels.first();
if (!channel) return
let announcement = args.slice(1).join(" ");
channel.send(announcement)
Error was how you passed in variables:
in one of your other command files you had:
execute(client, message, args) {
//this works
}
And in your announce command file you had:
execute(message, args){
console.log(message, args);
/* =>
Client {
...
}
Message {
...
}
*/
}
So in this instance, message is the actual client object, and args is the actual message object, so simply just fix your variable spots,
Your new execute function in announce.js
execute(client, message, args) {
//rest of code here
}

QueryFailedError: malformed array literal when I'm trying to insert json array in postgres using typeorm

I need to save json object with other nested objects into my postgres db. The json I'm receiving from user's browser.
I'm using Postgres 11.5 on AWS RDS. On backend I'm using NodeJS (NestJS/TypeScript/TypeORM).
I tried to convert each item of array to string using JSON.stringigy() but anyway I'm receiving error UnhandledPromiseRejectionWarning: QueryFailedError: malformed array literal: "[{"name":"Oviedo, Asturias, Spain"},{"name":"Oviedo, Asturias, Spain"}]"
Array looks like this:
"waypoints": [
{
"name": "Oviedo, Asturias, Spain"
},
{
"name": "Oviedo, Asturias, Spain"
}
]
This is a field to store the array above
#Column({ type: 'jsonb', array: true })
waypoints: any[];
And I assign data like this:
event.waypoints = eventData.waypoints;
// also I tried to do like this
event.waypoints = JSON.stringify([{ text: 'Some text' }, { text: 'Some text 2' }]);
Right now I'm receiving error:
(node:12833) UnhandledPromiseRejectionWarning: QueryFailedError: malformed array literal: "[{"name":"Oviedo, Asturias, Spain"},{"name":"Oviedo, Asturias, Spain"}]"
at new QueryFailedError (/home/banha/Projects/train-time-server/node_modules/typeorm/error/QueryFailedError.js:11:28)
at Query.callback (/home/banha/Projects/train-time-server/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:176:38)
at Query.handleError (/home/banha/Projects/train-time-server/node_modules/pg/lib/query.js:142:17)
at Connection.connectedErrorMessageHandler (/home/banha/Projects/train-time-server/node_modules/pg/lib/client.js:211:17)
at Connection.emit (events.js:209:13)
at Connection.EventEmitter.emit (domain.js:476:20)
at Socket.<anonymous> (/home/banha/Projects/train-time-server/node_modules/pg/lib/connection.js:126:12)
at Socket.emit (events.js:209:13)
at Socket.EventEmitter.emit (domain.js:476:20)
at addChunk (_stream_readable.js:305:12)
(node:12833) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12833) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

NodeJs Require module returns an empty object

I'm using NodeJS 8 LTS.
I have 3 js scripts where:
// main.js
const dom = require ('./Domains/Domains');
const factory = require ('./Domains/Factory');
(async () => {
const Domain = await factory.foo(); // <=== Error
})();
// Domains.js
class Domains {
constructor (options = {}) {
....
}
}
module.exports = Domains;
// Factory.js
const Domains = require('./Domains');
module.exports = {
foo: async () =>{
.... async stuff ...
return new Domains();
}
};
when I run main.js I get
(node:1816) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Domains is not a constructor
warning.js:18
(node:1816) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Debugging, I found that in Factory.js when it requires Domanis.js const Domains = require('./Domains'); it returns an empty object.
Looking around on internet I found that it happens when there are a circular dependencies between modules (Require returns an empty object) but It doesn't seem the case here.
Any idea?
Finally, I got the the issue's origin. The empty object was due to a circular dependency derived by another require that was inside Domains.js
// Domains.js
const another_module= require("circular_dep_creator");
class Domains {
constructor (options = {}) {
....
}
}
module.exports = Domains;
// circular_dep_creator.js
const factory = require ('./Domains/Factory');
...
another stuff
So, this causes a circular dependency that creates an empty object
The setImmediate call will delay the loading of the required module until the browser has finished doing what it needs to do. This may cause some issues where you try to use this module before it is loaded, but you could add checks for that.
// produces an empty object
const module = require('./someModule');
// produces the required object
let module;
setImmediate(() => {
module = required('./someModule');
});

Resources