Skip to content

Commit

Permalink
Latest changes
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinLemon112 committed Jul 1, 2024
1 parent a23e4bd commit 3260614
Show file tree
Hide file tree
Showing 11 changed files with 201 additions and 185 deletions.
74 changes: 38 additions & 36 deletions src/controllers/publishController.ts
Original file line number Diff line number Diff line change
@@ -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' });
// });
// };
120 changes: 61 additions & 59 deletions src/controllers/subscribeController.ts
Original file line number Diff line number Diff line change
@@ -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<SubscriptionInterface>({
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<SubscriptionInterface>('Subscription', subscriptionSchema);
// const subscriptionSchema = new Schema<SubscriptionInterface>({
// 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<SubscriptionInterface>('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' });
// };
30 changes: 30 additions & 0 deletions src/db.ts
Original file line number Diff line number Diff line change
@@ -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
};
30 changes: 21 additions & 9 deletions src/notification/publish/db.ts
Original file line number Diff line number Diff line change
@@ -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
};
dbURI,
connectToMongoDB
};
23 changes: 4 additions & 19 deletions src/notification/publish/publish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand All @@ -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 => {
Expand All @@ -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",
Expand All @@ -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' });
});
Expand Down
30 changes: 21 additions & 9 deletions src/notification/subscribe/db.ts
Original file line number Diff line number Diff line change
@@ -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
};
dbURI,
connectToMongoDB
};
Loading

0 comments on commit 3260614

Please sign in to comment.