0% found this document useful (0 votes)
12 views5 pages

MongoDB Chat Application Code

Uploaded by

nicodemuskiptoo8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views5 pages

MongoDB Chat Application Code

Uploaded by

nicodemuskiptoo8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

[Link]

com/
[Link]

// utils/[Link]

import { MongoClient } from 'mongodb';

const uri = [Link].MONGODB_URI;


const options = {};

let client;
let clientPromise;

if (![Link].MONGODB_URI) {
throw new Error('Please add your Mongo URI to .[Link]');
}

if ([Link].NODE_ENV === 'development') {


if (!global._mongoClientPromise) {
client = new MongoClient(uri, options);
global._mongoClientPromise = [Link]();
}
clientPromise = global._mongoClientPromise;
} else {
client = new MongoClient(uri, options);
clientPromise = [Link]();
}

export async function connectToDatabase() {


try {
await clientPromise;
return {
client,
db: [Link]('app-data')
};
} catch (error) {
[Link]('Error connecting to database:', error);
throw new Error('Failed to connect to database');
}
}

export { clientPromise };

.......app/utils/db
// utils/[Link]
import { MongoClient } from 'mongodb';

const uri = [Link].MONGODB_URI;


const options = {};

let client;

export async function connectToDatabase() {


if (!client) {
client = new MongoClient(uri, options);
await [Link]();
}
return {
client,
db: [Link]('app-data') // Replace 'app-data' with your actual database name
};
}

........
// pages/api/[Link]
import { connectToDatabase } from '../../utils/db';

export default async function handler(req, res) {


try {
const { db } = await connectToDatabase();
const messages = [Link]('messages');

if ([Link] === 'POST') {


const { username, content } = [Link];
const message = { username, content, timestamp: new Date() };

const result = await [Link](message);


message._id = [Link];
[Link](201).json(message);
} else if ([Link] === 'GET') {
const allMessages = await [Link]({}).toArray();
[Link](200).json(allMessages);
} else {
[Link](405).json({ message: 'Method not allowed' });
}
} catch (error) {
[Link]('Error handling messages:', error);
[Link](500).json({ message: 'Internal server error' });
}
}

.....
// [Link]

import { Server } from '[Link]';


import jwt from 'jsonwebtoken';
import { connectToDatabase } from './src/utils/db'; //
import { insertMessage, getAllMessages } from './src/utils/dbUtils'; //

const ioHandler = async (req, res) => {


if (![Link]) {
const io = new Server([Link]);
[Link] = io;

[Link](async (socket, next) => {


try {
const token = [Link];
if (!token) {
return next(new Error('Authentication error'));
}

const decoded = [Link](token, [Link].JWT_SECRET || '4737'); //


JWT secret
if (!decoded) {
return next(new Error('Invalid token'));
}

// Fetch user from database based on decoded username


const client = await connectToDatabase();
const db = [Link]('chat_app');
const users = [Link]('users');
const user = await [Link]({ username: [Link] });

if (!user) {
return next(new Error('User not found'));
}

[Link] = user; // Attach user object to socket for use in event


handlers
next();
} catch (error) {
next(new Error('Authentication error'));
}
});

[Link]('connection', (socket) => {


[Link]('New client connected');

// Load all messages when a client connects


[Link]('load_messages', async () => {
const allMessages = await getAllMessages();
[Link]('load_messages', allMessages);
});

// Handle send_message event


[Link]('send_message', async (message) => {
try {
// Store message in MongoDB
await insertMessage({
sender: [Link],
content: [Link],
timestamp: new Date()
});

// Emit message to all connected clients


[Link]('receive_message', {
sender: [Link],
content: [Link],
timestamp: new Date()
});
} catch (error) {
[Link]('Error sending message:', error);
}
});

[Link]('disconnect', () => {
[Link]('Client disconnected');
});
});
}
[Link]();
};
export default ioHandler;

....
// src/pages/[Link]

import React, { useEffect, useState } from 'react';


import axios from 'axios';
import { io, Socket } from '[Link]-client';
import Navbar from '../components/Navbar';
import MessageList from '../components/MessageList';
import MessageInput from '../components/MessageInput';
import ChatWindow from '../components/ChatWindow';
import Chat from '../components/Chat';

interface Message {
id: string;
content: string;
sender: string;
timestamp: string;
}

const Home: [Link] = () => {


const [messages, setMessages] = useState<Message[]>([]);
const socketRef = [Link]<Socket | null>(null);

useEffect(() => {
// Fetch messages from the API
[Link]('/api/messages')
.then((response) => {
const fetchedMessages = [Link]((msg: any) => ({
id: msg._id,
content: [Link],
sender: [Link],
timestamp: [Link]
}));
setMessages(fetchedMessages as Message[]);
})
.catch((error) => {
[Link]('Error fetching messages:', error);
});

// Initialize [Link]
const socket: Socket = io();
[Link] = socket;

[Link]('receive_message', (message: any) => {


const newMessage: Message = {
id: message._id,
content: [Link],
sender: [Link],
timestamp: [Link],
};
setMessages((prevMessages) => [...prevMessages, newMessage]);
});

return () => {
[Link]();
};
}, []);
const handleSendMessage = (content: string) => {
const newMessage: Message = {
id: 'temp-id', // Generate or replace with actual id logic
sender: 'Current User', // Replace with actual user logic
content,
timestamp: new Date().toISOString(),
};

[Link]('/api/messages', {
sender: [Link],
content: [Link],
})
.then((response) => {
const savedMessage = [Link];
setMessages((prevMessages) => [
...prevMessages,
{
id: savedMessage._id,
content: [Link],
sender: [Link],
timestamp: [Link],
},
]);
})
.catch((error) => {
[Link]('Error sending message:', error);
});

if ([Link]) {
[Link]('send_message', newMessage);
}
};

return (
<div>
<Navbar />
<main className="flex flex-col items-center justify-between p-24">
<Chat user={{ username: 'Current User' }}>
<ChatWindow>
<MessageList messages={messages} />
<MessageInput onSendMessage={handleSendMessage} />
</ChatWindow>
</Chat>
</main>
</div>
);
};

export default Home;

You might also like