groups are creating
This commit is contained in:
@@ -1,17 +1,19 @@
|
||||
import { useForm, SubmitHandler } from 'react-hook-form';
|
||||
import profile from '../../../assets/profile.svg';
|
||||
import { createRoom } from '../../socket/socket.tsx';
|
||||
import { useState } from 'react';
|
||||
import { useRef, useState } from 'react';
|
||||
import LoadingWheel from './LoadingWheel.tsx';
|
||||
import { axiosClient } from '../../App.tsx';
|
||||
type Contact = {
|
||||
contact: string | null;
|
||||
};
|
||||
|
||||
type Inputs = {
|
||||
roomName: string;
|
||||
groupName: string;
|
||||
};
|
||||
function ContactProfile({ contact }: Contact) {
|
||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||
const modalRef = useRef<HTMLDialogElement | null>(null);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
@@ -19,16 +21,21 @@ function ContactProfile({ contact }: Contact) {
|
||||
} = useForm<Inputs>();
|
||||
|
||||
const onSubmit: SubmitHandler<Inputs> = async (data) => {
|
||||
console.log('sent create room: ', data.roomName);
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const response = await createRoom(data.roomName);
|
||||
if (response?.status == 'ok') {
|
||||
const response = await axiosClient.post(
|
||||
`/api/chat/creategroup/${data.groupName}`,
|
||||
);
|
||||
console.log(response.data);
|
||||
if (response.data.group_id) {
|
||||
setIsLoading(false);
|
||||
console.log(`Create room status: ${response.status}`);
|
||||
if (modalRef.current) {
|
||||
modalRef.current.close();
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to create room: ', e);
|
||||
console.error('Failed to create group: ', e);
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
@@ -50,9 +57,9 @@ function ContactProfile({ contact }: Contact) {
|
||||
).showModal()
|
||||
}
|
||||
>
|
||||
create room
|
||||
Create group
|
||||
</button>
|
||||
<dialog id="my_modal_1" className="modal">
|
||||
<dialog id="my_modal_1" className="modal" ref={modalRef}>
|
||||
<div className="modal-box bg-gray-800 text-center relative p-1">
|
||||
<div className="absolute right-2 top-2">
|
||||
<form method="dialog">
|
||||
@@ -68,17 +75,17 @@ function ContactProfile({ contact }: Contact) {
|
||||
>
|
||||
<input
|
||||
className="input input-bordered bg-green-50 w-full text-black rounded-md text-center"
|
||||
{...register('roomName', {
|
||||
{...register('groupName', {
|
||||
required: true,
|
||||
minLength: 4,
|
||||
maxLength: 20,
|
||||
})}
|
||||
aria-invalid={errors.roomName ? 'true' : 'false'}
|
||||
aria-invalid={errors.groupName ? 'true' : 'false'}
|
||||
/>
|
||||
{errors.roomName?.type === 'minLength' && (
|
||||
{errors.groupName?.type === 'minLength' && (
|
||||
<p className="text-gray-300">room name is too short</p>
|
||||
)}
|
||||
{errors.roomName?.type === 'maxLength' && (
|
||||
{errors.groupName?.type === 'maxLength' && (
|
||||
<p className="text-gray-300">room name is too long</p>
|
||||
)}
|
||||
</form>
|
||||
|
||||
@@ -43,7 +43,7 @@ function MessagesArea({
|
||||
setIsFetchingHistory(true);
|
||||
fetchPreviousMessages(currentContact)
|
||||
.then(() => setIsLoading(false))
|
||||
.catch((e) => {
|
||||
.catch(() => {
|
||||
//console.error('Failed to fetch messages: ', e);
|
||||
setIsLoading(false);
|
||||
});
|
||||
|
||||
@@ -237,62 +237,16 @@ async function insertMessage(
|
||||
}
|
||||
}
|
||||
|
||||
async function getOrCreateConversation(senderUsername, receiverUsername) {
|
||||
// Check if a conversation between these two users already exists
|
||||
async function createGroup(groupname) {
|
||||
const query = `
|
||||
SELECT conversation_id
|
||||
FROM Conversations
|
||||
WHERE conversation_type = 'direct'
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM Memberships
|
||||
WHERE conversation_id = Conversations.conversation_id
|
||||
AND user_id = (SELECT user_id FROM Accounts WHERE username = $1)
|
||||
)
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM Memberships
|
||||
WHERE conversation_id = Conversations.conversation_id
|
||||
AND user_id = (SELECT user_id FROM Accounts WHERE username = $2)
|
||||
)
|
||||
LIMIT 1;
|
||||
INSERT INTO Conversations (conversation_type, name)
|
||||
VALUES ('group', $1)
|
||||
RETURNING conversation_id AS group_id;
|
||||
`;
|
||||
try {
|
||||
const result = await client.query(query, [
|
||||
senderUsername,
|
||||
receiverUsername,
|
||||
]);
|
||||
if (result.rows.length > 0) {
|
||||
return result.rows[0].conversation_id;
|
||||
} else {
|
||||
// Create a new conversation
|
||||
return await createConversation(senderUsername, receiverUsername);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to get or create conversation ", e);
|
||||
}
|
||||
}
|
||||
const result = await client.query(query, [groupname]);
|
||||
|
||||
async function createConversation(senderUsername, receiverUsername) {
|
||||
const query = `
|
||||
INSERT INTO Conversations (conversation_type)
|
||||
VALUES ('direct')
|
||||
RETURNING conversation_id;
|
||||
`;
|
||||
try {
|
||||
const result = await client.query(query);
|
||||
const conversation_id = result.rows[0].conversation_id;
|
||||
|
||||
// Add both users to the conversation
|
||||
await client.query(
|
||||
`
|
||||
INSERT INTO Memberships (conversation_id, user_id)
|
||||
VALUES ($1, (SELECT user_id FROM Accounts WHERE username = $2)), ($1, $3);
|
||||
`,
|
||||
[conversation_id, senderUsername, receiverUsername],
|
||||
);
|
||||
|
||||
return conversation_id;
|
||||
return result.rows[0].group_id;
|
||||
} catch (e) {
|
||||
console.error("Failed to create conversation ", e);
|
||||
}
|
||||
@@ -595,4 +549,5 @@ module.exports = {
|
||||
getContacts,
|
||||
updateContactStatus,
|
||||
updateContactLastActive,
|
||||
createGroup,
|
||||
};
|
||||
|
||||
@@ -36,7 +36,7 @@ const {
|
||||
} = require("./utils/filter");
|
||||
const { generateJwtToken, verifyJwtToken } = require("./auth/jwt");
|
||||
const { initializeSocket } = require("./socket/socket");
|
||||
const { getContacts, insertContact } = require("./db/db");
|
||||
const { getContacts, insertContact, createGroup } = require("./db/db");
|
||||
const { extname } = require("node:path");
|
||||
|
||||
const corsOptions = {
|
||||
@@ -303,6 +303,25 @@ app.post(
|
||||
},
|
||||
);
|
||||
|
||||
app.post(
|
||||
"/api/chat/creategroup/:groupname",
|
||||
authorizeUser,
|
||||
async (req, res) => {
|
||||
const groupname = req.params.groupname;
|
||||
if (!groupname) {
|
||||
res.status(400).json({ message: "Missing groupname parameter" });
|
||||
}
|
||||
const group_id = await createGroup(groupname);
|
||||
if (!group_id) {
|
||||
return res.status(500).json({ message: "Failed to create group" });
|
||||
}
|
||||
return res.status(200).json({
|
||||
message: `Successfully created group: ${groupname}`,
|
||||
group_id: group_id,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
initializeSocket(io);
|
||||
|
||||
server.listen(PORT, () => {
|
||||
|
||||
@@ -62,10 +62,6 @@ function initializeSocket(io) {
|
||||
return;
|
||||
}
|
||||
|
||||
socket.on("create room", async (msg, callback) => {
|
||||
const { roomName } = msg;
|
||||
callback({ status: "ok" });
|
||||
});
|
||||
socket.join(username); // join username room
|
||||
|
||||
socket.on("chat message", async (msg, callback) => {
|
||||
|
||||
Reference in New Issue
Block a user