Skip to content

Commit

Permalink
fixes for req routing
Browse files Browse the repository at this point in the history
  • Loading branch information
Sidd-77 committed Jan 2, 2025
1 parent f873294 commit 0eba2fa
Show file tree
Hide file tree
Showing 11 changed files with 52 additions and 48 deletions.
14 changes: 10 additions & 4 deletions apps/auth-service/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,18 @@ app.use(express.json());

const PORT = process.env.PORT || 5000;

app.use("/api/auth", router);

app.get("/health", (req, res) => {
res.send("Auth service is running...");
app.get("/api/auth/health", (req, res) => {
const healthStatus = {
service: "auth-service",
status: "healthy",
uptime: process.uptime(),
timestamp: new Date().toISOString(),
};
res.send(healthStatus);
});

app.use("/api/auth", router);

connectDB()
.then(() => {
app.listen(PORT, () => {
Expand Down
21 changes: 13 additions & 8 deletions apps/db-service/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,13 @@ async function processMessage(message: any) {
console.log("Message saved successfully:");
} catch (error) {
console.error("Error in message processing:", error);
throw error; // Rethrow to trigger message nack
throw error;
}
}

async function initializeServices() {
try {
await messageQueue.initialize();
// Set up message consumer
await messageQueue.consumeMessage(async (message: any) => {
await processMessage(message);
});
Expand All @@ -51,14 +50,20 @@ async function initializeServices() {
}
}

app.use("/api/users", userRoutes);
app.use("/api/chats", chatRoutes);
app.use("/api/messages", messageRoutes);

app.get("/health", (req, res) => {
res.send("DB Service is running...");
app.get("/api/db/health", (req, res) => {
const healthStatus = {
service: "db-service",
status: "healthy",
uptime: process.uptime(),
timestamp: new Date().toISOString(),
};
res.send(healthStatus);
});

app.use("/api/db/users", userRoutes);
app.use("/api/db/chats", chatRoutes);
app.use("/api/db/messages", messageRoutes);

connectDB()
.then(() => {
app.listen(PORT, () => {
Expand Down
13 changes: 10 additions & 3 deletions apps/file-service/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,19 @@ import fileRoutes from "./fileRoutes";
const app = express();
app.use(express.json());
app.use(cors());
app.use("/api/files", fileRoutes);

app.get("/health", (req, res) => {
res.send("File service is running...");
app.get("/api/files/health", (req, res) => {
const healthStatus = {
service: "file-service",
status: "healthy",
uptime: process.uptime(),
timestamp: new Date().toISOString(),
};
res.send(healthStatus);
});

app.use("/api/files", fileRoutes);

const PORT = process.env.PORT || 4300;
app.listen(PORT, () => {
console.log(`File service running on port ${PORT}`);
Expand Down
12 changes: 9 additions & 3 deletions apps/notification-service/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,17 @@ async function initializeServices() {
}
}

app.get("/health", (req: Request, res: Response) => {
res.send("Notification service is running...");
app.get("/api/notify/health", (req, res) => {
const healthStatus = {
service: "notification-service",
status: "healthy",
uptime: process.uptime(),
timestamp: new Date().toISOString(),
};
res.send(healthStatus);
});

app.use("/api", subscriptionRouter);
app.use("/api/notify", subscriptionRouter);

app.listen(PORT, () => {
mongoose
Expand Down
10 changes: 2 additions & 8 deletions apps/socket-service/src/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,10 @@ export class SocketService {
constructor(httpServer: HttpServer) {
this.io = new Server(httpServer, {
cors: {
origin: process.env.CLIENT_URL || "http://localhost:5173",
origin: "*",
methods: ["GET", "POST"],
},
path: "/api/socket",
});

this.publisher = new Redis(RedisURL);
Expand Down Expand Up @@ -122,20 +123,17 @@ export class SocketService {
}

private handleUserConnect(socketId: string, userId: string): void {
// Remove any existing connections for this user
this.onlineUsers = this.onlineUsers.filter(
(user) => user.userId !== userId
);

this.onlineUsers.push({ userId, socketId });

// Notify all users about the new online user
this.io.emit("user:status", {
userId,
status: "online",
});

// Send current online users list to the newly connected user
const onlineUserIds = this.onlineUsers.map((user) => user.userId);
this.io.to(socketId).emit("users:online", onlineUserIds);
}
Expand Down Expand Up @@ -167,7 +165,6 @@ export class SocketService {
createdAt: Date;
}): Promise<void> {
try {
// Publish message to Redis
await this.publisher.publish(CHANNELS.MESSAGE, JSON.stringify(data));
await this.messageQueue.pushMessage(data);
} catch (error) {
Expand All @@ -184,12 +181,10 @@ export class SocketService {
isfile: boolean;
createdAt: Date;
}): void {
// Get all relevant users
const relevantUsers = this.onlineUsers.filter(
(user) => user.userId === data.sender || user.userId === data.receiver
);

// Send message to online users
if (relevantUsers.length > 0) {
relevantUsers.forEach((user) => {
this.io.to(user.socketId).emit("message", {
Expand All @@ -199,7 +194,6 @@ export class SocketService {
});
}

// Check if receiver is offline and send notification
const isReceiverOffline = !this.onlineUsers.some(
(user) => user.userId === data.receiver
);
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/api/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ import { ChatMessage } from '../types/chat';
import { DB_URL } from '../config/env';

export const getMessages = async (chatId: string): Promise<ChatMessage[]> => {
return axios.post(`${DB_URL}/api/messages`, {chatId}).then((res) => res.data);
return axios.post(`${DB_URL}/api/db/messages`, {chatId}).then((res) => res.data);
}
2 changes: 1 addition & 1 deletion apps/web/src/api/notificationService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export class NotificationService {
},
};

const response = await fetch(`${NOTIFICATION_URL}/api/subscribe`, {
const response = await fetch(`${NOTIFICATION_URL}/api/notify/subscribe`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/api/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export class ChatSocketService {
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 1000,
path: '/api/socket',
});

this.setupSocketListeners();
Expand Down
6 changes: 3 additions & 3 deletions apps/web/src/api/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import { Chat } from '../types/chat';
import { DB_URL } from '../config/env';

export const searchUser = async (query:string): Promise<User[]> => {
return axios.post(`${DB_URL}/api/users/search`, {query}).then((res) => res.data);
return axios.post(`${DB_URL}/api/db/users/search`, {query}).then((res) => res.data);
}

export const createChat = async (userId1: string, userId2: string): Promise<Chat> => {
return axios.post(`${DB_URL}/api/chats/create`, {users:[userId1, userId2]}).then((res) => res.data);
return axios.post(`${DB_URL}/api/db/chats/create`, {users:[userId1, userId2]}).then((res) => res.data);
}

export const getChats = async (userId: string): Promise<Chat[]> => {
return axios.post(`${DB_URL}/api/chats`, {id:userId}).then((res) => res.data);
return axios.post(`${DB_URL}/api/db/chats`, {id:userId}).then((res) => res.data);
}
17 changes: 1 addition & 16 deletions apps/web/src/components/notificationSubscript.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@ import {
subscribeToPushNotifications,
} from "../lib/notificationHelper";
import { Button } from "@nextui-org/react";
import { NOTIFICATION_URL } from "../config/env";

export default function NotificationSubscribe({ userId }: { userId: string }) {
const [isSubscribed, setIsSubscribed] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);

// Check if subscriptionId is already stored in localStorage
useEffect(() => {
const subscriptionId = localStorage.getItem("pushSubscriptionId");
if (subscriptionId) {
Expand All @@ -24,24 +22,11 @@ export default function NotificationSubscribe({ userId }: { userId: string }) {
setError(null);

try {
// Check if the backend is accessible
const healthCheck = await fetch(
`${NOTIFICATION_URL}/health`,
{
method: "GET",
},
).catch(() => null);

if (!healthCheck) {
throw new Error(
"Backend server is not accessible. Please make sure it's running on the correct port.",
);
}

const swRegistration = await registerServiceWorker();
const { subscriptionId } = await subscribeToPushNotifications(swRegistration, userId);
console.log("Subscription ID:", subscriptionId);
// Store subscription ID in localStorage

if (subscriptionId) {
localStorage.setItem("pushSubscriptionId", subscriptionId);
}
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/lib/notificationHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export async function subscribeToPushNotifications(
});

// Send subscription to backend with additional info
const response = await fetch(`${NOTIFICATION_URL}/api/subscribe`, {
const response = await fetch(`${NOTIFICATION_URL}/api/notify/subscribe`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Expand Down

0 comments on commit 0eba2fa

Please sign in to comment.