-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.controller.ts
50 lines (45 loc) · 1.22 KB
/
app.controller.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
import { Controller } from '@nestjs/common';
import {
Ctx,
EventPattern,
KafkaContext,
Payload,
} from '@nestjs/microservices';
import { createWriteStream } from 'node:fs'
import * as csv from 'fast-csv'
type MyEvent = {
publishedTimestamp: number
}
@Controller()
export class AppController {
private csv: csv.CsvFormatterStream<csv.FormatterRow, csv.FormatterRow>
constructor() {
const file = createWriteStream('/app/outputs/consumer.csv')
this.csv = csv.format({ headers: true })
this.csv.pipe(file).on('end', () => file.close())
}
@EventPattern('my_event')
async handleMyEvent(
@Payload() event: MyEvent,
@Ctx() context: KafkaContext
) {
const topic = context.getTopic();
const partition = context.getPartition();
const { offset } = context.getMessage();
try {
const id = context.getMessage().key
console.log(`>>> Got message id=${id}`)
this.csv.write({ published: event.publishedTimestamp, consumed: Date.now(), id})
} catch (error) {
console.error(error)
} finally {
await context.getConsumer().commitOffsets([
{
topic,
partition,
offset: (Number(offset) + 1).toString(),
},
]);
}
}
}