UNPKG

1.64 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 if (!this.keepBinary) {
11 data.value = this.decode(data.value);
12 }
13 if (!(0, shared_utils_1.isNil)(data.key)) {
14 data.key = this.decode(data.key);
15 }
16 if (!(0, shared_utils_1.isNil)(data.headers)) {
17 const decodeHeaderByKey = (key) => {
18 data.headers[key] = this.decode(data.headers[key]);
19 };
20 Object.keys(data.headers).forEach(decodeHeaderByKey);
21 }
22 else {
23 data.headers = {};
24 }
25 return data;
26 }
27 decode(value) {
28 if ((0, shared_utils_1.isNil)(value)) {
29 return null;
30 }
31 // A value with the "leading zero byte" indicates the schema payload.
32 // The "content" is possibly binary and should not be touched & parsed.
33 if (Buffer.isBuffer(value) &&
34 value.length > 0 &&
35 value.readUInt8(0) === 0) {
36 return value;
37 }
38 let result = value.toString();
39 const startChar = result.charAt(0);
40 // only try to parse objects and arrays
41 if (startChar === '{' || startChar === '[') {
42 try {
43 result = JSON.parse(value.toString());
44 }
45 catch (e) { }
46 }
47 return result;
48 }
49}
50exports.KafkaParser = KafkaParser;