UNPKG

1.84 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.KafkaParser = void 0;
4const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
5class KafkaParser {
6 constructor(config) {
7 this.keepBinary = (config && config.keepBinary) || false;
8 }
9 parse(data) {
10 // Clone object to as modifying the original one would break KafkaJS retries
11 const result = Object.assign(Object.assign({}, data), { headers: Object.assign({}, data.headers) });
12 if (!this.keepBinary) {
13 result.value = this.decode(data.value);
14 }
15 if (!(0, shared_utils_1.isNil)(data.key)) {
16 result.key = this.decode(data.key);
17 }
18 if (!(0, shared_utils_1.isNil)(data.headers)) {
19 const decodeHeaderByKey = (key) => {
20 result.headers[key] = this.decode(data.headers[key]);
21 };
22 Object.keys(data.headers).forEach(decodeHeaderByKey);
23 }
24 else {
25 result.headers = {};
26 }
27 return result;
28 }
29 decode(value) {
30 if ((0, shared_utils_1.isNil)(value)) {
31 return null;
32 }
33 // A value with the "leading zero byte" indicates the schema payload.
34 // The "content" is possibly binary and should not be touched & parsed.
35 if (Buffer.isBuffer(value) &&
36 value.length > 0 &&
37 value.readUInt8(0) === 0) {
38 return value;
39 }
40 let result = value.toString();
41 const startChar = result.charAt(0);
42 // only try to parse objects and arrays
43 if (startChar === '{' || startChar === '[') {
44 try {
45 result = JSON.parse(value.toString());
46 }
47 catch (e) { }
48 }
49 return result;
50 }
51}
52exports.KafkaParser = KafkaParser;