-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
85 lines (76 loc) · 2.5 KB
/
index.js
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
80
81
82
83
84
85
require("dotenv").config();
const express = require("express");
const { graphqlHTTP } = require("express-graphql");
const schema = require("./schema.js");
const connectDB = require("./database.js");
const KafkaService = require("./KafkaService.js");
console.log("KafkaService imported:", KafkaService);
// Import necessary modules
const app = express();
console.log("Environment Variables:");
console.log("PORT:", process.env.PORT);
console.log("DATABASE_URL:", process.env.DATABASE_URL);
console.log("KAFKA_BROKER!!:", process.env.KAFKA_BROKER);
// Filter out falsy values and setup Kafka brokers
const kafkaBrokers = [process.env.KAFKA_BROKER].filter(Boolean);
console.log("Kafka Brokers:", kafkaBrokers);
const kafkaService = new KafkaService(kafkaBrokers);
console.log("KafkaService instance created: ", kafkaService);
// Connect to MongoDB
connectDB()
.then(() => console.log("MongoDB connected successfully"))
.catch((err) => console.error("MongoDB connection error:", err));
// Middleware for json parsing
app.use(express.json());
// GraphQL endpoint setup
app.use(
"/graphql",
graphqlHTTP({
schema: schema,
graphiql: true,
})
);
// Set up a basic route
app.get("/", (req, res) => {
res.send("GraphQL API Running");
});
// Start the server
const PORT = process.env.PORT || 9000;
const server = app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
connectKafkaWithRetry(5);
});
// Function to manage retries for Kafka connection
function connectKafkaWithRetry(retries) {
kafkaService
.connect()
.then(() => {
console.log("Kafka Producer connected successfully.");
})
.catch((err) => {
console.error("Kafka connection error:", err);
if (retries > 0) {
console.log(`Retrying Kafka connection... (${retries} retries left)`);
setTimeout(() => connectKafkaWithRetry(retries - 1), 5000);
} else {
console.error("Failed to connect to Kafka after retries.");
}
});
}
// Function to handle graceful shutdown on receiving termination signals
function handleShutdown(signal) {
console.log(`${signal} signal received: closing HTTP server`);
server.close(async () => {
console.log("HTTP server closed");
try {
await kafkaService.disconnect();
console.log("Kafka Producer disconnected successfully.");
} catch (err) {
console.error("Failed to disconnect Kafka Producer:", err);
} finally {
process.exit();
}
});
}
process.on("SIGINT", handleShutdown);
process.on("SIGTERM", handleShutdown);