Skip to content

Commit

Permalink
Latest changes
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinLemon112 committed Jun 24, 2024
1 parent 6af4352 commit 9d82fbe
Show file tree
Hide file tree
Showing 7 changed files with 70 additions and 52 deletions.
22 changes: 11 additions & 11 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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/"
Expand All @@ -40,7 +40,7 @@ services:
volumes:
- ./src/notification/publish:/app
ports:
- 4000:4000
- 6000:6000
networks:
- backend
depends_on:
Expand Down
17 changes: 0 additions & 17 deletions src/controllers/publishController.ts
Original file line number Diff line number Diff line change
@@ -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();

Expand All @@ -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);
Expand Down
12 changes: 10 additions & 2 deletions src/controllers/userController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,18 @@ export const registerUser = async (req: Request, res: Response): Promise<void> =
}

// 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' });
}
};
Expand Down
6 changes: 3 additions & 3 deletions src/models/DeviceSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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: {
Expand All @@ -40,7 +40,7 @@ const DeviceSchema: Schema = new mongoose.Schema({
type: String,
},
colorTimestamp: {
type: String,
type: Date, // Corrected to Date
},
brightness: {
type: Number,
Expand Down
4 changes: 2 additions & 2 deletions src/notification/publish/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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/
Expand Down
26 changes: 23 additions & 3 deletions src/notification/publish/publish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 = {
Expand Down
35 changes: 21 additions & 14 deletions src/server/server.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand All @@ -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();

Expand Down Expand Up @@ -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());
Expand Down

0 comments on commit 9d82fbe

Please sign in to comment.