Skip to content

Commit

Permalink
Updated the id provider
Browse files Browse the repository at this point in the history
  • Loading branch information
SurajjBhardwaj committed Feb 25, 2024
1 parent e19208a commit 375458d
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 20 deletions.
20 changes: 0 additions & 20 deletions models/roomId.js

This file was deleted.

24 changes: 24 additions & 0 deletions models/roomIdModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import mongoose from "mongoose";

const roomIdSchema = new mongoose.Schema(
{
roomId: {
type: String,
required: true,
unique: true,
},
joinedPeople: {
type: Number,
default: 1,
max: 2,
},
lang: {
type: String,
required: true,
},
},
{ timestamps: true }
);

mongoose.models = {};
export default mongoose.model("roomId", roomIdSchema);
40 changes: 40 additions & 0 deletions pages/api/idProvider.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import connectDB from "@/lib/connectDB";
import RoomId from "@/models/roomIdModel";

export default async function handler(req, res) {
await connectDB();

if (req.method === "POST") {
try {

const { techStack } = req.body;

await connectDB();
// Generate a random room id string
const randomRoomId = Math.random().toString(36).substring(2, 7);

// Find a room id which is recently created or if the user count is less than 2
let room = await RoomId.findOne({ $and: [{ joinedPeople: { $lt: 2 } },{lang:techStack}] });

// If no available room is found, create a new one
if (!room) {
room = new RoomId({
roomId: randomRoomId,
lang:techStack,
});
await room.save();
} else {
// If an available room is found, increase the joinedPeople count by 1
room.joinedPeople += 1;
await room.save();
}

res.status(200).json({ roomId: room.roomId });
} catch (error) {
console.error("Error:", error);
res.status(500).json({ error: error.message });
}
} else {
res.status(405).json({ error: "Method Not Allowed" });
}
}

0 comments on commit 375458d

Please sign in to comment.