Skip to content

Commit

Permalink
created API for creating chats
Browse files Browse the repository at this point in the history
  • Loading branch information
AishaAgarwal committed Jan 3, 2024
1 parent 1cb8d61 commit 6978b73
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
7 changes: 4 additions & 3 deletions models/Chat.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import mongoose from "mongoose";
const Chatmodel=mongoose.Schema({
chatName:{type:String,trim:true},
chatName:{type:String,trim:true, index: true},
isGroupchat:{type:Boolean,default:false},
users:[{type:mongoose.Schema.Types.ObjectId,ref:'User'}],
latestMessage:{type:mongoose.Schema.Types.ObjectId,ref:'Message'},
users:[{type:mongoose.Schema.Types.ObjectId,ref:'User', index: true}],
latestMessage:{type:mongoose.Schema.Types.ObjectId,ref:'Message', sender: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
receiver: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },},
groupAdmin:{type:mongoose.Schema.Types.ObjectId,ref:'User'},

},{timestamps:true})
Expand Down
31 changes: 31 additions & 0 deletions src/pages/api/chats/create.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import connectDb from "../../../middleware/mongoose";
import Chat from "../../../../models/Chat";

const handler = async (req, res) => {
if (req.method == 'POST'){
try{
const {chatName, isGroupChat, users, groupAdmin} = req.body;

const chat = new Chat({
chatName,
isGroupChat,
users,
groupAdmin,
})

await chat.save();

res.status(200).json({message: "Chat created successfully", chat});
}
catch (error){
console.error('Error creating chat: ', error);
res.status(500).json({error: "Internal server error"});
}

}
else{
res.status(400).json({error: "Bad request"});
}
}

export default connectDb(handler);

0 comments on commit 6978b73

Please sign in to comment.