Skip to content

Commit a725eba

Browse files
committed
fix(microservices): fix kafka serilization of class instances
Fix serilization of class instances that doesn't have own toString() implementation and therefore inherit the standard behavior of [object Object]. Add test for inherited classes.
1 parent b6d4188 commit a725eba

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

packages/microservices/serializers/kafka-request.serializer.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,9 @@ export class KafkaRequestSerializer
4343
!isNil(value) && !isString(value) && !Buffer.isBuffer(value);
4444

4545
if (isObjectOrArray) {
46-
return isPlainObject(value) || Array.isArray(value)
46+
return isPlainObject(value) ||
47+
Array.isArray(value) ||
48+
value.toString == Object.prototype.toString // Prevent default [object Object] behavior
4749
? JSON.stringify(value)
4850
: value.toString();
4951
} else if (isUndefined(value)) {

packages/microservices/test/serializers/kafka-request.serializer.spec.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,22 @@ describe('KafkaRequestSerializer', () => {
7575
});
7676
});
7777

78+
it('complex object with inherited .toString()', async () => {
79+
class ComplexParent {
80+
private readonly name = 'complexParent';
81+
public toString(): string {
82+
return this.name;
83+
}
84+
}
85+
86+
class ComplexChild extends ComplexParent {}
87+
88+
expect(await instance.serialize(new ComplexChild())).to.deep.eq({
89+
headers: {},
90+
value: 'complexParent',
91+
});
92+
});
93+
7894
it('complex object without .toString()', async () => {
7995
class ComplexWithOutToString {
8096
private readonly name = 'complex';
@@ -83,7 +99,7 @@ describe('KafkaRequestSerializer', () => {
8399
expect(await instance.serialize(new ComplexWithOutToString())).to.deep.eq(
84100
{
85101
headers: {},
86-
value: '[object Object]',
102+
value: '{"name":"complex"}',
87103
},
88104
);
89105
});

0 commit comments

Comments
 (0)