UNPKG

@nestjs/microservices

Version:

Nest - modern, fast, powerful node.js web framework (@microservices)

54 lines (53 loc) 1.62 kB
import { isNil } from '@nestjs/common/internal'; export class KafkaParser { keepBinary; constructor(config) { this.keepBinary = (config && config.keepBinary) || false; } parse(data) { // Clone object to as modifying the original one would break KafkaJS retries const result = { ...data, headers: { ...data.headers }, }; if (!this.keepBinary) { result.value = this.decode(data.value); } if (!isNil(data.key)) { result.key = this.decode(data.key); } if (!isNil(data.headers)) { for (const key of Object.keys(data.headers)) { result.headers[key] = this.decode(data.headers[key]); } } else { result.headers = {}; } return result; } decode(value) { if (isNil(value)) { return null; } // A value with the "leading zero byte" indicates the schema payload. // The "content" is possibly binary and should not be touched & parsed. if (Buffer.isBuffer(value) && value.length > 0 && value.readUInt8(0) === 0) { return value; } let result = value.toString(); const startChar = result.charAt(0); // Only try to parse objects and arrays if (startChar === '{' || startChar === '[') { try { result = JSON.parse(value.toString()); } catch (e) { // Do nothing } } return result; } }