Skip to content

Commit b5d8965

Browse files
committed
add tests for @MessageRequests for complex data types.
1 parent f906ec8 commit b5d8965

7 files changed

Lines changed: 201 additions & 45 deletions

File tree

integration/microservices/e2e/sum-kafka.spec.ts

Lines changed: 74 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,58 @@
1-
import { INestApplication } from '@nestjs/common';
2-
import { Transport } from '@nestjs/microservices';
1+
import {
2+
ArgumentsHost,
3+
Catch,
4+
ExceptionFilter,
5+
HttpException,
6+
INestApplication,
7+
RpcExceptionFilter,
8+
} from '@nestjs/common';
9+
import { RpcException, Transport } from '@nestjs/microservices';
310
import { Test } from '@nestjs/testing';
411
import { expect } from 'chai';
512
import * as request from 'supertest';
613
import { KafkaController } from '../src/kafka/kafka.controller';
14+
import { APP_FILTER } from '@nestjs/core';
15+
import { Observable, throwError } from 'rxjs';
16+
import { KafkaMessagesController } from '../src/kafka/kafka.messages.controller';
17+
import { UserDto } from '../src/kafka/dtos/user.dto';
18+
import { UserEntity } from '../src/kafka/entities/user.entity';
19+
import { BusinessDto } from '../src/kafka/dtos/business.dto';
20+
import { BusinessEntity } from '../src/kafka/entities/business.entity';
21+
22+
@Catch()
23+
class KafkaExceptionFilter implements ExceptionFilter {
24+
catch(exception: HttpException, host: ArgumentsHost): any {
25+
console.log(exception);
26+
}
27+
}
28+
@Catch()
29+
class RpcErrorFilter implements RpcExceptionFilter {
30+
catch(exception: RpcException): Observable<any> {
31+
console.log(exception);
32+
return throwError(exception);
33+
}
34+
}
735

836
describe('Kafka transport', () => {
937
let server;
1038
let app: INestApplication;
1139

1240
it(`Start Kafka app`, async () => {
1341
const module = await Test.createTestingModule({
14-
controllers: [KafkaController],
42+
controllers: [
43+
KafkaController,
44+
KafkaMessagesController,
45+
],
46+
providers: [
47+
{
48+
provide: APP_FILTER,
49+
useClass: RpcErrorFilter,
50+
},
51+
{
52+
provide: APP_FILTER,
53+
useClass: KafkaExceptionFilter,
54+
},
55+
],
1556
}).compile();
1657

1758
app = module.createNestApplication();
@@ -37,30 +78,43 @@ describe('Kafka transport', () => {
3778
.expect(200, '15');
3879
}).timeout(50000);
3980

40-
// it(`/POST (async command sum)`, done => {
41-
// request(server)
42-
// .post('/?command=math.sum')
43-
// .send([1, 2, 3, 4, 5])
44-
// .end(() => {
45-
// setTimeout(() => {
46-
// expect(KafkaController.MATH_SUM).to.eq(15);
47-
// done();
48-
// }, 4000);
49-
// });
50-
// }).timeout(5000);
51-
5281
it(`/POST (async event notification)`, done => {
5382
request(server)
5483
.post('/notify')
55-
.send([1, 2, 3, 4, 5])
84+
.send()
5685
.end(() => {
57-
setTimeout(() => {
58-
expect(KafkaController.IS_NOTIFIED).to.be.true;
59-
done();
60-
}, 4000);
86+
expect(KafkaController.IS_NOTIFIED).to.be.true;
87+
done();
6188
});
6289
}).timeout(5000);
6390

91+
const userDto: UserDto = {
92+
email: 'enriquebenavidesm@gmail.com',
93+
name: 'Ben',
94+
phone: '1112223331',
95+
years: 33,
96+
};
97+
const newUser: UserEntity = new UserEntity(userDto);
98+
const businessDto: BusinessDto = {
99+
name: 'Example',
100+
phone: '2233441122',
101+
user: newUser,
102+
};
103+
it(`/POST (async command create user)`, () => {
104+
return request(server)
105+
.post('/user')
106+
.send(userDto)
107+
.expect(200);
108+
}).timeout(50000);
109+
110+
it(`/POST (async command create business`, () => {
111+
const newBusiness: BusinessEntity = new BusinessEntity(businessDto);
112+
return request(server)
113+
.post('/business')
114+
.send(businessDto)
115+
.expect(200);
116+
}).timeout(50000);
117+
64118
after(`Stopping Kafka app`, async () => {
65119
await app.close();
66120
});
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { UserEntity } from '../entities/user.entity';
2+
3+
export class BusinessDto {
4+
name: string;
5+
phone: string;
6+
user: UserEntity;
7+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export class UserDto {
2+
name: string;
3+
email: string;
4+
phone: string;
5+
years: number;
6+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { UserEntity } from './user.entity';
2+
import { BusinessDto } from '../dtos/business.dto';
3+
4+
export class BusinessEntity {
5+
constructor(business: BusinessDto) {
6+
this.id = Math.random() * 99999999;
7+
this.name = business.name;
8+
this.phone = business.phone;
9+
this.createdBy = {
10+
id: business.user.id,
11+
};
12+
this.created = new Date();
13+
}
14+
id: number;
15+
name: string;
16+
phone: string;
17+
createdBy: Partial<UserEntity>;
18+
created: Date;
19+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { UserDto } from '../dtos/user.dto';
2+
3+
export class UserEntity {
4+
constructor(user: UserDto) {
5+
this.id = Math.random() * 99999999;
6+
this.name = user.name;
7+
this.email = user.email;
8+
this.phone = user.phone;
9+
this.years = user.years;
10+
this.created = new Date();
11+
}
12+
id: number;
13+
name: string;
14+
email: string;
15+
phone: string;
16+
years: number;
17+
created: Date;
18+
}
Lines changed: 30 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,18 @@
1-
import { Body, Controller, HttpCode, Post, Query, OnModuleInit } from '@nestjs/common';
1+
import { Body, Controller, HttpCode, Post, Query } from '@nestjs/common';
22
import {
33
Client,
44
ClientProxy,
5-
EventPattern,
6-
MessagePattern,
75
Transport,
86
MessageRequest,
97
} from '@nestjs/microservices';
108
import { Logger } from '@nestjs/common/services/logger.service';
11-
import * as util from 'util';
129

1310
import { Observable } from 'rxjs';
14-
import * as Bluebird from 'bluebird';
11+
import { UserDto } from './dtos/user.dto';
12+
import { BusinessDto } from './dtos/business.dto';
1513

1614
@Controller()
17-
export class KafkaController implements OnModuleInit {
15+
export class KafkaController {
1816
protected readonly logger = new Logger(KafkaController.name);
1917
static IS_NOTIFIED = false;
2018
static MATH_SUM = 0;
@@ -29,10 +27,6 @@ export class KafkaController implements OnModuleInit {
2927
})
3028
private readonly client: ClientProxy;
3129

32-
public async onModuleInit(){
33-
await this.client.connect();
34-
}
35-
3630
@Post()
3731
@HttpCode(200)
3832
@MessageRequest('math.sum', 'math.sum.reply')
@@ -46,28 +40,39 @@ export class KafkaController implements OnModuleInit {
4640
numbers: data,
4741
},
4842
}).toPromise();
49-
50-
// await Bluebird.delay(30000);
51-
52-
this.logger.error(util.format('@Query math.sum result %o', result));
53-
5443
return result.value;
5544
}
5645

57-
@MessagePattern('math.sum')
58-
mathSum(data: any){
59-
this.logger.error(util.format('@MessagePattern math.sum data %o', data));
60-
61-
return (data.value.numbers || []).reduce((a, b) => a + b);
62-
}
63-
6446
@Post('notify')
6547
async sendNotification(): Promise<any> {
6648
return this.client.emit('notify', {notify: true});
6749
}
6850

69-
@EventPattern('notify')
70-
eventHandler(data: any) {
71-
KafkaController.IS_NOTIFIED = data.value.notify;
51+
// Complex data to send.
52+
@Post('/user')
53+
@HttpCode(200)
54+
@MessageRequest('user.create', 'user.create.reply')
55+
async createUser(@Body() user: UserDto): Promise<Observable<any>> {
56+
const result = await this.client.send('user.create', {
57+
key: '1',
58+
value: {
59+
user,
60+
},
61+
}).toPromise();
62+
return result.value;
63+
}
64+
65+
// Complex data to send.
66+
@Post('/business')
67+
@HttpCode(200)
68+
@MessageRequest('business.create', 'business.create.reply')
69+
async createBusiness(@Body() business: BusinessDto) {
70+
const result = await this.client.send('business.create', {
71+
key: '1',
72+
value: {
73+
business,
74+
},
75+
}).toPromise();
76+
return result.value;
7277
}
7378
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { Controller } from '@nestjs/common';
2+
import { Client, ClientProxy, EventPattern, MessagePattern, MessageRequest, Transport } from '@nestjs/microservices';
3+
import { Logger } from '@nestjs/common/services/logger.service';
4+
import { KafkaController } from './kafka.controller';
5+
import { BusinessDto } from './dtos/business.dto';
6+
import { UserEntity } from './entities/user.entity';
7+
import { BusinessEntity } from './entities/business.entity';
8+
import * as util from 'util';
9+
import { UserDto } from './dtos/user.dto';
10+
11+
@Controller()
12+
export class KafkaMessagesController {
13+
protected readonly logger = new Logger(KafkaMessagesController.name);
14+
static IS_NOTIFIED = false;
15+
static MATH_SUM = 0;
16+
17+
@Client({
18+
transport: Transport.KAFKA,
19+
options: {
20+
client: {
21+
brokers: ['localhost:9092'],
22+
},
23+
},
24+
})
25+
private readonly client: ClientProxy;
26+
27+
@MessagePattern('math.sum')
28+
mathSum(data: any){
29+
return (data.value.numbers || []).reduce((a, b) => a + b);
30+
}
31+
32+
@EventPattern('notify')
33+
eventHandler(data: any) {
34+
KafkaController.IS_NOTIFIED = data.value.notify;
35+
}
36+
37+
// Complex data to send.
38+
@MessagePattern('user.create')
39+
async createUser(params: {value: { user: UserDto } }) {
40+
return new UserEntity(params.value.user);
41+
}
42+
43+
@MessagePattern('business.create')
44+
async createBusiness(params: {value: {business: BusinessDto}}) {
45+
return new BusinessEntity(params.value.business);
46+
}
47+
}

0 commit comments

Comments
 (0)