Skip to content

Commit 8c40d92

Browse files
author
niki
committed
feat: Передача и парсинг json в потоках
Closes #85
1 parent 6713166 commit 8c40d92

File tree

4 files changed

+49
-0
lines changed

4 files changed

+49
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { Transform, TransformCallback, TransformOptions } from 'stream';
2+
3+
class BufferToJsonTransform<T> extends Transform {
4+
private head: Buffer | undefined;
5+
private errors = {
6+
CONVERSION_ERROR: 'Не удалось преобразовать данные',
7+
};
8+
constructor(options: TransformOptions) {
9+
super({ objectMode: true, highWaterMark: 10, ...options });
10+
}
11+
async _transform(tail: Buffer, _: BufferEncoding, cb: TransformCallback) {
12+
let partnerParams: T | undefined;
13+
try {
14+
try {
15+
if (this.head) {
16+
tail = Buffer.concat([this.head, Buffer.from(tail)]);
17+
partnerParams = JSON.parse(tail.toString());
18+
this.head = undefined;
19+
} else {
20+
partnerParams = JSON.parse(tail.toString());
21+
}
22+
} catch (err) {
23+
this.head = Buffer.from(tail);
24+
cb();
25+
}
26+
27+
if (partnerParams) {
28+
cb(null, partnerParams);
29+
}
30+
} catch (error) {
31+
console.error(this.errors.CONVERSION_ERROR, tail.toString());
32+
if (error instanceof Error) {
33+
cb(error);
34+
} else {
35+
cb(new Error(this.errors.CONVERSION_ERROR));
36+
}
37+
}
38+
}
39+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { Transform, TransformCallback } from 'stream';
2+
3+
export class JsonToBufferTransform<T> extends Transform {
4+
transform(chunk: T, encoding: BufferEncoding, cb: TransformCallback) {
5+
cb(null, Buffer.from(JSON.stringify(chunk)));
6+
}
7+
}

src/StreamOptions/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export * from './JsonToBufferTransform';
2+
export * from './BufferToJsonTransform';

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ export * from './Method';
44
export * from './injector';
55
export * from './Container';
66
export * from './interfaces';
7+
export * from './StreamOptions';

0 commit comments

Comments
 (0)