-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
79 lines (71 loc) · 1.92 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import stream, { WritableOptions } from 'stream';
import { Client } from '@elastic/elasticsearch'
import { BufferEncoding } from 'typescript';
interface ElasticsearchConfig {
host: string;
index: string;
type: string;
auth: any;
cloud: any;
node: any;
}
class ElasticsearchWritableStream extends stream.Writable {
private config: ElasticsearchConfig;
private client: Client;
constructor(config: ElasticsearchConfig, options?: WritableOptions) {
super(options);
this.config = config;
this.client = new Client({
cloud: this.config.cloud,
auth: this.config.auth,
node: this.config.node,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
}
_destroy(): Promise<void> {
return this.client.close();
}
async _write(
body: any,
enc: BufferEncoding,
next: any
): Promise<void> {
try {
await this.client.index({
index: this.config.index,
body: body.toString()
})
next();
} catch (err) {
next(err);
}
}
async _writev(
chunks: Array<{ chunk: any; encoding: BufferEncoding }>,
next: any
): Promise<void> {
const body = chunks
.map((chunk) => chunk.chunk)
.reduce((arr, obj) => {
arr.push({ index: {} });
arr.push(obj);
return arr;
}, []);
try {
await this.client.bulk({
index: this.config.index,
body: body.toString()
});
next();
} catch (err) {
next(err);
}
}
}
export default (options: ElasticsearchConfig) => {
const sink = new ElasticsearchWritableStream(options);
return sink;
}