Skip to content

Commit

Permalink
Latest changes
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinLemon112 committed Jun 25, 2024
1 parent 9d82fbe commit 8a494c5
Show file tree
Hide file tree
Showing 8 changed files with 84 additions and 25 deletions.
4 changes: 3 additions & 1 deletion docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,14 @@ services:
- activemq

subscribe:
container_name: subscribe
container_name: "subscribe"
build:
context: 'src/notification/subscribe'
env_file: ".env"
volumes:
- ./src/notification/subscribe:/app
ports:
- 7000:7000
networks:
- backend
depends_on:
Expand Down
33 changes: 17 additions & 16 deletions src/controllers/subscribeController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,27 @@ client.on('message', async (receivedTopic, msg) => {
console.log(`Message received: ${message}`);

// MongoDB logic for handling received message
try {
interface Subscription extends Document {
id: string;
message: string;
}
try {
interface SubscriptionInterface extends Document {
id: string;
message: string;
}

const subscriptionSchema = new Schema<Subscription>({
id: String,
message: String,
});
const subscriptionSchema = new Schema<SubscriptionInterface>({
id: String,
message: String,
});

const SubscriptionModel = mongoose.model<Subscription>('Subscription', subscriptionSchema);
// Check if the model already exists before defining it
const SubscriptionModel = mongoose.models.Subscription || mongoose.model<SubscriptionInterface>('Subscription', subscriptionSchema);

const subscription = {
id: uuidv4(),
message: message,
};
const subscription = {
id: uuidv4(),
message: message,
};

await SubscriptionModel.create(subscription);
} catch (error) {
await SubscriptionModel.create(subscription);
} catch (error) {

// Simulate a 404 error
if (!message) {
Expand Down
16 changes: 13 additions & 3 deletions src/controllers/userController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,24 @@ export const getUserById = async (req: Request, res: Response): Promise<void> =>
// Delete user by ID
export const deleteUserById = async (req: Request, res: Response): Promise<void> => {
try {
const deletedUser: UserInterface | null = await User.findByIdAndDelete(req.params.id);
// Find the user by ID
const user: UserInterface | null = await User.findById(req.params.id);

if (!deletedUser) {
if (!user) {
res.status(404).json({ error: 'User not found' });
return;
}

res.json({ message: 'User deleted successfully' });
// Delete associated devices
const deviceIds = user.devicesLinked;
if (deviceIds.length > 0) {
await Device.deleteMany({ _id: { $in: deviceIds } });
}

// Delete the user
const deletedUser: UserInterface | null = await User.findByIdAndDelete(req.params.id);

res.json({ message: 'User and associated devices deleted successfully' });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
Expand Down
3 changes: 3 additions & 0 deletions src/notification/subscribe/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ FROM node:18-bullseye
# Specifies app directory as working directory in docker image
WORKDIR /app

# Exposes port 7000 which is the same port specified in the express app in subscribe.ts
EXPOSE 7000

# Copy config files to app directory in docker image
COPY package.json /app/

Expand Down
18 changes: 18 additions & 0 deletions src/notification/subscribe/db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
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

mongoose.connect(dbURI);

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
});

export default {
dbURI
};
29 changes: 28 additions & 1 deletion src/notification/subscribe/subscribe.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import mqtt, { MqttClient } from 'mqtt';
import dotenv from 'dotenv';
import express from 'express';
import mongoose, { ConnectOptions } from "mongoose";
import dbConfig from './db'; // Import MongoDB configuration from db.ts

dotenv.config();

const app = express();
const port = process.env.PORT || 7000;

const options = {
username: process.env.ACTIVE_MQ_USERNAME,
password: process.env.ACTIVE_MQ_PASSWORD,
Expand All @@ -14,6 +19,26 @@ const topic = process.env.ACTIVE_MQ_TOPIC as string; // Type assertion

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}`);
process.exit(1); // Exit process if MongoDB connection or server startup fails
});

client.on('connect', () => {
console.log("Broker connected");
client.subscribe(topic, (err) => {
Expand Down Expand Up @@ -42,4 +67,6 @@ const subscribeRouter = express.Router();
// res.send('Subscribe endpoint');
// });

export { subscribeRouter };
app.listen(port, () => {
console.log(`Subscribe service is running on port ${port}`);
});
4 changes: 1 addition & 3 deletions src/routes/publishRoutes.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import express from 'express';
import {
publishMessage,
} from '../controllers/publishController';
import { publishMessage } from '../controllers/publishController';

const router = express.Router();

Expand Down
2 changes: 1 addition & 1 deletion src/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ async function connectToMongoDB() {

// Connect to MongoDB and start the server
connectToMongoDB().catch(error => {
console.error(`Error starting Publish service: ${error}`);
console.error(`Error starting Server service: ${error}`);
process.exit(1); // Exit process if MongoDB connection or server startup fails
});

Expand Down

0 comments on commit 8a494c5

Please sign in to comment.