diff --git a/src/rabbit.ts b/src/rabbit.ts index 66405f6..aeccdba 100644 --- a/src/rabbit.ts +++ b/src/rabbit.ts @@ -134,15 +134,27 @@ export class Rabbit { private parseContent(content: Buffer, content_type?: string): RabbitContentType { let final_content: RabbitContentType = content; - if (content_type === 'application/json') { - final_content = JSON.parse(content.toString()); - } - else if (content_type === 'text/string') { - final_content = content.toString(); + if (content_type) { + if (content_type === 'application/json') { + final_content = JSON.parse(content.toString()); + } + else if (content_type === 'text/string') { + final_content = content.toString(); + } + else if (content_type === 'text/number') { + final_content = parseFloat(content.toString()); + } } - else if (content_type === 'text/number') { - final_content = parseFloat(content.toString()); + else { + try { + final_content = content.toString(); + final_content = JSON.parse(final_content); + } + catch (e) { + // pass + } } + return final_content; } @@ -188,7 +200,9 @@ export class Rabbit { */ public async publishTopic(topic: string, content: RabbitContentType = Buffer.from(''), options: amqplib.Options.Publish = {}): Promise { const encodedContent = this.encodeContent(content); - options.contentType = options.contentType || this.getContentType(content); + if (options.contentType === undefined) { + options.contentType = this.getContentType(content); + } const channel = await this.pch; await channel.checkExchange(this.exchange); return channel.publish(this.exchange, topic, encodedContent, options); diff --git a/test/rabbit.spec.ts b/test/rabbit.spec.ts index f757a35..f549506 100644 --- a/test/rabbit.spec.ts +++ b/test/rabbit.spec.ts @@ -89,3 +89,20 @@ test('rpc with replyTo', (done) => { expect(msg).toBeNull; }); }); + +test('no content-type set', (done) => { + const io = new Io({cogPath: rabbitCog}); + expect(io.rabbit).toBeInstanceOf(Rabbit); + if (!io.rabbit) { + return expect(true).toBeFalsy; + } + + const topicName = `test.topic.${uuidv4().replace('-', '')}`; + io.rabbit.onTopic(topicName, (msg) => { + expect(msg.properties.contentType).toBeNull; + expect(msg.content).toStrictEqual({hello: 'world'}); + (io.rabbit).close().then(done()); + }); + + io.rabbit.publishTopic(topicName, {hello: 'world'}, {contentType: ''}); +});