Repository navigation
Expand file tree
/
Copy pathdatabase-processor.js
More file actions
66 lines (56 loc) · 1.64 KB
/
Copy pathdatabase-processor.js
File metadata and controls
66 lines (56 loc) · 1.64 KB
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
import 'dotenv/config';
import mongoose from 'mongoose';
import { kafkaClient } from './kafka-client.js';
import { Location } from './models/Location.js';
async function init() {
try {
if (!process.env.MONGO_URI) {
console.error('Missing MONGO_URI in environment configuration');
process.exit(1);
}
await mongoose.connect(process.env.MONGO_URI);
const kafkaConsumer = kafkaClient.consumer({
groupId: 'database-processor',
});
await kafkaConsumer.connect();
await kafkaConsumer.subscribe({
topics: ['location-updates'],
fromBeginning: true,
});
await kafkaConsumer.run({
eachMessage: async ({ message, heartbeat }) => {
try {
const data = JSON.parse(message.value.toString());
await Location.create({
userId: data.id,
latitude: data.latitude,
longitude: data.longitude,
timestamp: new Date(),
});
} catch (dbError) {
if (dbError instanceof SyntaxError || dbError.name === 'ValidationError') {
console.error('Skipped bad location record:', dbError.message);
} else {
throw dbError;
}
}
await heartbeat();
},
});
const shutdown = async () => {
try {
await kafkaConsumer.disconnect();
await mongoose.disconnect();
process.exit(0);
} catch {
process.exit(1);
}
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
} catch (err) {
console.error('Database processor initialization failed:', err.message);
process.exit(1);
}
}
init();