diff --git a/src/controllers/publishController.ts b/src/controllers/publishController.ts index 9446749f..effd24db 100644 --- a/src/controllers/publishController.ts +++ b/src/controllers/publishController.ts @@ -1,41 +1,43 @@ -import { Request, Response } from 'express'; -import mqtt, { MqttClient } from 'mqtt'; -import { v1 as uuidv1 } from 'uuid'; -import dotenv from 'dotenv'; -dotenv.config(); +// TODO: Remove, deprecate, or archive unused commented out code -const options = { - username: process.env.ACTIVE_MQ_USERNAME, - password: process.env.ACTIVE_MQ_PASSWORD, - clientId: `publish_${uuidv1()}`, - port: 1883, -}; -const topic = process.env.ACTIVE_MQ_TOPIC as string; // Type assertion +// import { Request, Response } from 'express'; +// import mqtt, { MqttClient } from 'mqtt'; +// import { v1 as uuidv1 } from 'uuid'; +// import dotenv from 'dotenv'; +// dotenv.config(); -// Publish message to MQTT -export const publishMessage = async (req: Request, res: Response) => { - const client: MqttClient = mqtt.connect(process.env.ACTIVE_MQ_ENDPOINT as string, options); +// const options = { +// username: process.env.ACTIVE_MQ_USERNAME, +// password: process.env.ACTIVE_MQ_PASSWORD, +// clientId: `publish_${uuidv1()}`, +// port: 1883, +// }; +// const topic = process.env.ACTIVE_MQ_TOPIC as string; // Type assertion - const event = { - id: req.params.id, - message: "From Publish Service", - }; +// // Publish message to MQTT +// export const publishMessage = async (req: Request, res: Response) => { +// const client: MqttClient = mqtt.connect(process.env.ACTIVE_MQ_ENDPOINT as string, options); - client.on('connect', () => { - console.log("Broker connected"); - client.publish(topic, JSON.stringify(event), {}, (err) => { - if (err) { - console.error(`Error publishing message: ${err}`); - res.status(500).json({ error: 'Internal Server Error' }); - } else { - client.end(); - res.json(event); - } - }); - }); +// const event = { +// id: req.params.id, +// message: "From Publish Service", +// }; - client.on('error', (error) => { - console.log(error); - res.status(500).json({ error: 'Internal Server Error' }); - }); -}; +// client.on('connect', () => { +// console.log("Broker connected"); +// client.publish(topic, JSON.stringify(event), {}, (err) => { +// if (err) { +// console.error(`Error publishing message: ${err}`); +// res.status(500).json({ error: 'Internal Server Error' }); +// } else { +// client.end(); +// res.json(event); +// } +// }); +// }); + +// client.on('error', (error) => { +// console.log(error); +// res.status(500).json({ error: 'Internal Server Error' }); +// }); +// }; diff --git a/src/controllers/subscribeController.ts b/src/controllers/subscribeController.ts index 17f9142c..41888378 100644 --- a/src/controllers/subscribeController.ts +++ b/src/controllers/subscribeController.ts @@ -1,74 +1,76 @@ -import { Request, Response } from 'express'; -import mqtt, { MqttClient } from 'mqtt'; -import { v4 as uuidv4 } from 'uuid'; -import mongoose, { Schema, Document } from 'mongoose'; -import dotenv from 'dotenv'; -dotenv.config(); +// // TODO: Remove, deprecate, or archive unused commented out code -const options = { - username: process.env.ACTIVE_MQ_USERNAME, - password: process.env.ACTIVE_MQ_PASSWORD, - clientId: `subscribe_${uuidv4()}`, - port: 1883, -}; +// import { Request, Response } from 'express'; +// import mqtt, { MqttClient } from 'mqtt'; +// import { v4 as uuidv4 } from 'uuid'; +// import mongoose, { Schema, Document } from 'mongoose'; +// import dotenv from 'dotenv'; +// dotenv.config(); -const topic = process.env.ACTIVE_MQ_TOPIC as string; // Type assertion -const client: MqttClient = mqtt.connect(process.env.ACTIVE_MQ_ENDPOINT as string, options); // Type assertion +// const options = { +// username: process.env.ACTIVE_MQ_USERNAME, +// password: process.env.ACTIVE_MQ_PASSWORD, +// clientId: `subscribe_${uuidv4()}`, +// port: 1883, +// }; -client.on('connect', () => { - client.subscribe(topic); -}); +// const topic = process.env.ACTIVE_MQ_TOPIC as string; // Type assertion +// const client: MqttClient = mqtt.connect(process.env.ACTIVE_MQ_ENDPOINT as string, options); // Type assertion -let message: string | null = null; +// client.on('connect', () => { +// client.subscribe(topic); +// }); -client.on('message', async (receivedTopic, msg) => { - console.log(`Message received on topic ${receivedTopic}`); - message = msg.toString(); - console.log(`Message received: ${message}`); +// let message: string | null = null; - // MongoDB logic for handling received message - try { - interface SubscriptionInterface extends Document { - id: string; - message: string; - } +// client.on('message', async (receivedTopic, msg) => { +// console.log(`Message received on topic ${receivedTopic}`); +// message = msg.toString(); +// console.log(`Message received: ${message}`); - const subscriptionSchema = new Schema({ - id: String, - message: String, - }); +// // MongoDB logic for handling received message +// try { +// interface SubscriptionInterface extends Document { +// id: string; +// message: string; +// } - // Check if the model already exists before defining it - const SubscriptionModel = mongoose.models.Subscription || mongoose.model('Subscription', subscriptionSchema); +// const subscriptionSchema = new Schema({ +// id: String, +// message: String, +// }); - const subscription = { - id: uuidv4(), - message: message, - }; +// // Check if the model already exists before defining it +// const SubscriptionModel = mongoose.models.Subscription || mongoose.model('Subscription', subscriptionSchema); - await SubscriptionModel.create(subscription); -} catch (error) { +// const subscription = { +// id: uuidv4(), +// message: message, +// }; - // Simulate a 404 error - if (!message) { - throw { status: 404, message: 'Not Found' }; - } +// await SubscriptionModel.create(subscription); +// } catch (error) { - // Simulate a 403 error - if (message === 'Forbidden') { - throw { status: 403, message: 'Forbidden' }; - } +// // Simulate a 404 error +// if (!message) { +// throw { status: 404, message: 'Not Found' }; +// } - // Simulate a 401 error - if (message === 'Unauthorized') { - throw { status: 401, message: 'Unauthorized' }; - } +// // Simulate a 403 error +// if (message === 'Forbidden') { +// throw { status: 403, message: 'Forbidden' }; +// } + +// // Simulate a 401 error +// if (message === 'Unauthorized') { +// throw { status: 401, message: 'Unauthorized' }; +// } - console.error(error); - } -}); +// console.error(error); +// } +// }); -// Check subscription status -export const checkSubscriptionStatus = (req: Request, res: Response) => { - res.status(200).json({ message: 'Subscriber is running' }); -}; +// // Check subscription status +// export const checkSubscriptionStatus = (req: Request, res: Response) => { +// res.status(200).json({ message: 'Subscriber is running' }); +// }; diff --git a/src/db.ts b/src/db.ts new file mode 100644 index 00000000..4b0d974e --- /dev/null +++ b/src/db.ts @@ -0,0 +1,30 @@ +import mongoose from 'mongoose'; +import dotenv from 'dotenv'; + +dotenv.config(); + +const dbURI = `mongodb+srv://${process.env.MONGO_DB_USER}:${process.env.MONGO_DB_PASS}@luminositycluster-0.cgornhw.mongodb.net/Luminosity`; + +let isConnected = false; + +export const connectToMongoDB = async () => { + if (isConnected) { + console.log('MongoDB connection is already established'); + return; + } + + try { + await mongoose.connect(dbURI, { + }); + isConnected = true; + console.log('Connected to MongoDB'); + } catch (error) { + console.error(`Error connecting to MongoDB: ${error}`); + process.exit(1); // Exit process on connection error + } +}; + +export default { + dbURI, + connectToMongoDB +}; diff --git a/src/notification/publish/db.ts b/src/notification/publish/db.ts index 1d19dd0d..4b0d974e 100644 --- a/src/notification/publish/db.ts +++ b/src/notification/publish/db.ts @@ -1,18 +1,30 @@ import mongoose from 'mongoose'; import dotenv from 'dotenv'; + dotenv.config(); -const dbURI = `mongodb+srv://${process.env.MONGO_DB_USER}:${process.env.MONGO_DB_PASS}@luminositycluster-0.cgornhw.mongodb.net/Luminosity`; //MongoDb Connection String +const dbURI = `mongodb+srv://${process.env.MONGO_DB_USER}:${process.env.MONGO_DB_PASS}@luminositycluster-0.cgornhw.mongodb.net/Luminosity`; -mongoose.connect(dbURI); +let isConnected = false; -const db = mongoose.connection; +export const connectToMongoDB = async () => { + if (isConnected) { + console.log('MongoDB connection is already established'); + return; + } -db.on('error', console.error.bind(console, 'MongoDB connection error:')); -db.once('open', () => { - console.log('Connected to MongoDB'); -}); + try { + await mongoose.connect(dbURI, { + }); + isConnected = true; + console.log('Connected to MongoDB'); + } catch (error) { + console.error(`Error connecting to MongoDB: ${error}`); + process.exit(1); // Exit process on connection error + } +}; export default { - dbURI -}; \ No newline at end of file + dbURI, + connectToMongoDB +}; diff --git a/src/notification/publish/publish.ts b/src/notification/publish/publish.ts index 6a284b26..dc4222f6 100644 --- a/src/notification/publish/publish.ts +++ b/src/notification/publish/publish.ts @@ -2,8 +2,7 @@ import mqtt, { MqttClient } from 'mqtt'; import { v1 as uuidv1 } from 'uuid'; import dotenv from 'dotenv'; import express from 'express'; -import mongoose, { ConnectOptions } from "mongoose"; -import dbConfig from './db'; // Import MongoDB configuration from db.t +import { connectToMongoDB } from './db'; // Import the singleton connection function dotenv.config(); @@ -16,21 +15,7 @@ const options = { clientId: `publish_${uuidv1()}`, port: 1883, }; -const topic = process.env.ACTIVE_MQ_TOPIC as string; // Type assertion - -// MongoDB connection setup -async function connectToMongoDB() { - try { - await mongoose.connect(dbConfig.dbURI, { - useNewUrlParser: true, - useUnifiedTopology: true, - } as ConnectOptions); - console.log('Connected to MongoDB'); - } catch (error) { - console.error(`Error connecting to MongoDB: ${error}`); - process.exit(1); // Exit process on connection error - } -} +const topic = process.env.ACTIVE_MQ_TOPIC as string; // Connect to MongoDB and start the server connectToMongoDB().catch(error => { @@ -39,7 +24,7 @@ connectToMongoDB().catch(error => { }); app.get("/publish/:id", async (req, res) => { - const client: MqttClient = mqtt.connect(process.env.ACTIVE_MQ_ENDPOINT as string, options); // Type assertion + const client: MqttClient = mqtt.connect(process.env.ACTIVE_MQ_ENDPOINT as string, options); const event = { id: req.params.id, message: "From Publish Service", @@ -58,7 +43,7 @@ app.get("/publish/:id", async (req, res) => { }); }); - client.on('error', (error) => { + client.on('error', (error: Error) => { console.log(error); res.status(500).json({ error: 'Internal Server Error' }); }); diff --git a/src/notification/subscribe/db.ts b/src/notification/subscribe/db.ts index 1d19dd0d..4b0d974e 100644 --- a/src/notification/subscribe/db.ts +++ b/src/notification/subscribe/db.ts @@ -1,18 +1,30 @@ import mongoose from 'mongoose'; import dotenv from 'dotenv'; + dotenv.config(); -const dbURI = `mongodb+srv://${process.env.MONGO_DB_USER}:${process.env.MONGO_DB_PASS}@luminositycluster-0.cgornhw.mongodb.net/Luminosity`; //MongoDb Connection String +const dbURI = `mongodb+srv://${process.env.MONGO_DB_USER}:${process.env.MONGO_DB_PASS}@luminositycluster-0.cgornhw.mongodb.net/Luminosity`; -mongoose.connect(dbURI); +let isConnected = false; -const db = mongoose.connection; +export const connectToMongoDB = async () => { + if (isConnected) { + console.log('MongoDB connection is already established'); + return; + } -db.on('error', console.error.bind(console, 'MongoDB connection error:')); -db.once('open', () => { - console.log('Connected to MongoDB'); -}); + try { + await mongoose.connect(dbURI, { + }); + isConnected = true; + console.log('Connected to MongoDB'); + } catch (error) { + console.error(`Error connecting to MongoDB: ${error}`); + process.exit(1); // Exit process on connection error + } +}; export default { - dbURI -}; \ No newline at end of file + dbURI, + connectToMongoDB +}; diff --git a/src/notification/subscribe/subscribe.ts b/src/notification/subscribe/subscribe.ts index 801addec..e9d78b4c 100644 --- a/src/notification/subscribe/subscribe.ts +++ b/src/notification/subscribe/subscribe.ts @@ -2,8 +2,7 @@ import mqtt, { MqttClient } from 'mqtt'; import dotenv from 'dotenv'; import express from 'express'; import { Request, Response } from 'express'; -import mongoose, { ConnectOptions } from "mongoose"; -import dbConfig from './db'; // Import MongoDB configuration from db.ts +import { connectToMongoDB } from './db'; // Import the singleton connection function dotenv.config(); @@ -13,27 +12,13 @@ const port = process.env.PORT || 7000; const options = { username: process.env.ACTIVE_MQ_USERNAME, password: process.env.ACTIVE_MQ_PASSWORD, - clientId: `subscribe_${Math.random().toString(16).substr(2, 8)}`, // Generate random client ID + clientId: `subscribe_${Math.random().toString(16).substr(2, 8)}`, port: 1883, }; -const topic = process.env.ACTIVE_MQ_TOPIC as string; // Type assertion +const topic = process.env.ACTIVE_MQ_TOPIC as string; const client: MqttClient = mqtt.connect(process.env.ACTIVE_MQ_ENDPOINT as string, options); -// MongoDB connection setup -async function connectToMongoDB() { - try { - await mongoose.connect(dbConfig.dbURI, { - useNewUrlParser: true, - useUnifiedTopology: true, - } as ConnectOptions); - console.log('Connected to MongoDB'); - } catch (error) { - console.error(`Error connecting to MongoDB: ${error}`); - process.exit(1); // Exit process on connection error - } -} - // Connect to MongoDB and start the server connectToMongoDB().catch(error => { console.error(`Error starting Subscribe service: ${error}`); @@ -53,16 +38,14 @@ client.on('connect', () => { client.on('message', (topic, message) => { console.log(`Received message from topic ${topic}: ${message.toString()}`); - // Process the received message as needed }); -client.on('error', (error) => { +client.on('error', (error: Error) => { console.error(error); }); const subscribeRouter = express.Router(); -// Check subscription status subscribeRouter.get('/status', (req: Request, res: Response) => { res.status(200).json({ message: 'Subscriber is running' }); }); diff --git a/src/routes/publishRoutes.ts b/src/routes/publishRoutes.ts index fd5ad1ea..e7fc7f21 100644 --- a/src/routes/publishRoutes.ts +++ b/src/routes/publishRoutes.ts @@ -1,8 +1,10 @@ -import express from 'express'; -import { publishMessage } from '../controllers/publishController'; +// TODO: Remove, deprecate, or archive unused commented out code -const router = express.Router(); +// import express from 'express'; +// import { publishMessage } from '../controllers/publishController'; -router.get('/:id', publishMessage); +// const router = express.Router(); -export default router; +// router.get('/:id', publishMessage); + +// export default router; diff --git a/src/routes/subscribeRoutes.ts b/src/routes/subscribeRoutes.ts index d2bfd3c1..5099bc3f 100644 --- a/src/routes/subscribeRoutes.ts +++ b/src/routes/subscribeRoutes.ts @@ -1,8 +1,10 @@ -import express from 'express'; -import { checkSubscriptionStatus } from '../controllers/subscribeController'; +// TODO: Remove, deprecate, or archive unused commented out code -const router = express.Router(); +// import express from 'express'; +// import { checkSubscriptionStatus } from '../controllers/subscribeController'; -router.get('/status', checkSubscriptionStatus); +// const router = express.Router(); -export default router; +// router.get('/status', checkSubscriptionStatus); + +// export default router; diff --git a/src/server/server.ts b/src/server/server.ts index 23615d09..0fee5dc9 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -1,14 +1,13 @@ import express from "express"; -import mongoose, { ConnectOptions } from "mongoose"; import dotenv from "dotenv"; import cors from "cors"; // import routeURLs from "../routes/routes"; <- DEPRECATED import userRouter from "../routes/userRoutes"; -import publishRouter from "../routes/publishRoutes"; -import subscribeRouter from "../routes/subscribeRoutes"; +// import publishRouter from "../routes/publishRoutes"; <- DEPRECATED +// import subscribeRouter from "../routes/subscribeRoutes"; <- DEPRECATED -import dbConfig from '../notification/publish/db'; // Import MongoDB configuration from db.ts +import { connectToMongoDB } from '../db'; // Import the singleton connection function // TODO: Remove, deprecate, or archive unused commented out code // dotenv.config(); @@ -44,20 +43,6 @@ dotenv.config(); const app = express(); const port = process.env.PORT || 4000; -// MongoDB connection setup -async function connectToMongoDB() { - try { - await mongoose.connect(dbConfig.dbURI, { - useNewUrlParser: true, - useUnifiedTopology: true, - } as ConnectOptions); - console.log('Connected to MongoDB'); - } catch (error) { - console.error(`Error connecting to MongoDB: ${error}`); - process.exit(1); // Exit process on connection error - } -} - // Connect to MongoDB and start the server connectToMongoDB().catch(error => { console.error(`Error starting Server service: ${error}`); @@ -73,8 +58,8 @@ app.use(cors()); // app.use("/app", routeURLs); // Existing routes <- DEPRECATED app.use("/users", userRouter); // User service routes -app.use("/publish", publishRouter); // Publish service routes -app.use("/subscribe", subscribeRouter); // Subscribe service routes +// app.use("/publish", publishRouter); // Publish service routes <- DEPRECATED +// app.use("/subscribe", subscribeRouter); // Subscribe service routes <- DEPRECATED // Start the server app.listen(port, () => { diff --git a/src/tsconfig.json b/src/tsconfig.json index c93d9d18..3557cff5 100644 --- a/src/tsconfig.json +++ b/src/tsconfig.json @@ -76,7 +76,8 @@ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ /* Type Checking */ - "strict": true, /* Enable all strict type-checking options. */ + "strict": true, + /* Enable all strict type-checking options. */ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ @@ -99,5 +100,5 @@ /* Completeness */ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ "skipLibCheck": true /* Skip type checking all .d.ts files. */ - } + } } \ No newline at end of file