diff --git a/docker-compose.yaml b/docker-compose.yaml index a6137a45..dfa3cc72 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -11,16 +11,16 @@ services: - "1883:1883" env_file: ".env" - # server: - # build: "." - # command: "npm run server" - # ports: - # - "4000:4000" - # networks: - # - backend - # env_file: ".env" - # depends_on: - # - "activemq" + server: + build: "." + command: "npm run server" + ports: + - "4000:4000" + networks: + - backend + env_file: ".env" + depends_on: + - "activemq" account: container_name: "account" build: "src/account/" @@ -40,7 +40,7 @@ services: volumes: - ./src/notification/publish:/app ports: - - 4000:4000 + - 6000:6000 networks: - backend depends_on: diff --git a/src/controllers/publishController.ts b/src/controllers/publishController.ts index f748b261..9446749f 100644 --- a/src/controllers/publishController.ts +++ b/src/controllers/publishController.ts @@ -1,7 +1,6 @@ import { Request, Response } from 'express'; import mqtt, { MqttClient } from 'mqtt'; import { v1 as uuidv1 } from 'uuid'; -import mongoose from 'mongoose'; import dotenv from 'dotenv'; dotenv.config(); @@ -13,22 +12,6 @@ const options = { }; const topic = process.env.ACTIVE_MQ_TOPIC as string; // Type assertion -// Establish Mongoose connection -// MongoDB URL -const URL = process.env.MONGO_DB_URL; - -// Verify that URL is defined -if (URL) { - const mongo_connect = mongoose.createConnection(URL); - mongo_connect.on(`error`, console.error.bind(console, `connection error:`)); - mongo_connect.once(`open`, () => { - // Successful connection! - console.log("MongoDB database connection established successfully"); - }); -} else { - console.error("MongoDB URL is not defined in .env file."); -} - // 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); diff --git a/src/controllers/userController.ts b/src/controllers/userController.ts index 34d4742e..a360d7d5 100644 --- a/src/controllers/userController.ts +++ b/src/controllers/userController.ts @@ -39,10 +39,18 @@ export const registerUser = async (req: Request, res: Response): Promise = } // Save the user with linked devices - const savedUser: UserInterface = await newUser.save(); + let savedUser: UserInterface | null = await newUser.save(); + + // Populate the devicesLinked field + savedUser = await User.findById(savedUser._id).populate('devicesLinked').exec(); + + if (!savedUser) { + throw new Error('User not found after saving'); + } + res.status(201).json(savedUser); } catch (error) { - console.error(error); + console.error('Error saving user:', error); res.status(500).json({ error: 'Internal Server Error' }); } }; diff --git a/src/models/DeviceSchema.ts b/src/models/DeviceSchema.ts index 7c07f65f..fa1fab6c 100644 --- a/src/models/DeviceSchema.ts +++ b/src/models/DeviceSchema.ts @@ -8,7 +8,7 @@ export interface DeviceInterface extends Document { connected?: boolean; connectedTimestamp?: Date | null; color?: string; - colorTimestamp?: string; + colorTimestamp?: Date | null; // Corrected to Date brightness?: number; brightnessTimestamp?: Date | null; } @@ -21,7 +21,7 @@ const DeviceSchema: Schema = new mongoose.Schema({ }, lastUpdated: { type: Date, - default: new Date(), + default: Date.now, // Corrected to use Date.now required: true, }, powered: { @@ -40,7 +40,7 @@ const DeviceSchema: Schema = new mongoose.Schema({ type: String, }, colorTimestamp: { - type: String, + type: Date, // Corrected to Date }, brightness: { type: Number, diff --git a/src/notification/publish/Dockerfile b/src/notification/publish/Dockerfile index 552157f3..07fe85f5 100644 --- a/src/notification/publish/Dockerfile +++ b/src/notification/publish/Dockerfile @@ -4,8 +4,8 @@ FROM node:18-bullseye # Specifies app directory as working directory in docker image WORKDIR /app -# Exposes port 4000 which is the same port specified in the express app in publish.ts -EXPOSE 4000 +# Exposes port 6000 which is the same port specified in the express app in publish.ts +EXPOSE 6000 # Copy config files to app directory in docker image COPY package.json /app/ diff --git a/src/notification/publish/publish.ts b/src/notification/publish/publish.ts index e63de814..6a284b26 100644 --- a/src/notification/publish/publish.ts +++ b/src/notification/publish/publish.ts @@ -2,13 +2,13 @@ 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 mongoose for MongoDB connection -import dbConfig from './db'; // Import MongoDB configuration from db.ts +import mongoose, { ConnectOptions } from "mongoose"; +import dbConfig from './db'; // Import MongoDB configuration from db.t dotenv.config(); const app = express(); -const port = process.env.PORT || 4000; +const port = process.env.PORT || 6000; const options = { username: process.env.ACTIVE_MQ_USERNAME, @@ -18,6 +18,26 @@ const options = { }; 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 + } +} + +// Connect to MongoDB and start the server +connectToMongoDB().catch(error => { + console.error(`Error starting Publish service: ${error}`); + process.exit(1); // Exit process if MongoDB connection or server startup fails +}); + app.get("/publish/:id", async (req, res) => { const client: MqttClient = mqtt.connect(process.env.ACTIVE_MQ_ENDPOINT as string, options); // Type assertion const event = { diff --git a/src/server/server.ts b/src/server/server.ts index c4b5fb77..9996ffe8 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -1,5 +1,5 @@ import express from "express"; -import mongoose from "mongoose"; +import mongoose, { ConnectOptions } from "mongoose"; import dotenv from "dotenv"; import cors from "cors"; @@ -8,6 +8,8 @@ import userRouter from "../routes/userRoutes"; import publishRouter from "../routes/publishRoutes"; import subscribeRouter from "../routes/subscribeRoutes"; +import dbConfig from '../notification/publish/db'; // Import MongoDB configuration from db.ts + // TODO: Remove, deprecate, or archive unused commented out code // dotenv.config(); @@ -42,21 +44,26 @@ dotenv.config(); const app = express(); const port = process.env.PORT || 4000; -// MongoDB URL -const URL = process.env.MONGO_DB_URL; - -// Verify that URL is defined -if (URL) { - const mongo_connect = mongoose.createConnection(URL); - mongo_connect.on(`error`, console.error.bind(console, `connection error:`)); - mongo_connect.once(`open`, () => { - // Successful connection! - console.log("MongoDB database connection established successfully"); - }); -} else { - console.error("MongoDB URL is not defined in .env file."); +// 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 Publish service: ${error}`); + process.exit(1); // Exit process if MongoDB connection or server startup fails +}); + // Middleware setup app.use(express.json()); app.use(cors());