minor changes

This commit is contained in:
slawk0
2024-10-13 00:12:50 +02:00
parent 0b0c162bff
commit bd78e7c817
7 changed files with 56 additions and 17 deletions

View File

@@ -0,0 +1,18 @@
import io from "socket.io-client";
import Cookie from "js-cookie";
import { useEffect, useState } from "react";
const socket = io({
auth: {
token: Cookie.get("token"),
},
});
function chatArea() {
const [messages, setMessages] = useState<string>("");
useEffect(() => {
socket.on("historical", (historical: string) => {
setMessages((prevMessages) => [...prevMessages, messages]);
});
}, []);
}

View File

@@ -1,6 +1,10 @@
import { useForm, SubmitHandler } from "react-hook-form";
import zdjecie from "../../assets/walter.png";
import { sendMessage, sendContact } from "../socket/socket.tsx";
import {
sendMessage,
sendContact,
sendRequestHistorical,
} from "../socket/socket.tsx";
import { useEffect, useState } from "react";
type Input = {
message: string;
@@ -15,18 +19,19 @@ function Chat() {
formState: { errors },
} = useForm<Input>();
const [contact, setContact] = useState<string>("");
const [messages, setMessages] = useState<string>("");
useEffect(() => {
const storedContact = localStorage.getItem("contact");
if (storedContact) {
setContact(storedContact);
sendRequestHistorical(storedContact);
}
}, []);
// Sending message
const submitMessage: SubmitHandler<Input> = (data) => {
// block sending empty message
if (!data.message) {
if (!data.message || !contact) {
return;
}
console.log("sended message: " + data.message + " recipient: ", contact);
@@ -53,7 +58,7 @@ function Chat() {
<div className="text-center">
<form onSubmit={handleSubmit(submitContact)}>
<input
className="text-black bg-green-100 pl-2 rounded-md shadow-lg h-8 mb-2"
className="text-black bg-green-100 pl-2 shadow-lg rounded-md h-8 mb-2 mt-2"
type="text"
placeholder="Enter contact"
{...register("contact", {
@@ -78,6 +83,7 @@ function Chat() {
</ul>
</div>
{/*Profile element*/}
<hr />
<div className="flex items-center">
<div className="m-3 rounded-full w-12 h-12 overflow-hidden ">
<img
@@ -105,11 +111,11 @@ function Chat() {
</ul>
</div>
{/*Messages input*/}
<div className="mt-auto">
<div className="mt-auto mb-2">
<form onSubmit={handleSubmit(submitMessage)}>
<div className="flex">
<input
className="bg-green-100 text-black rounded-md w-full ml-1 mr-1"
className="bg-green-100 text-black rounded-md w-full ml-1 mr-1 size-10"
type="text"
placeholder="Enter message"
{...register("message", {

View File

@@ -33,6 +33,7 @@ export default function Signup() {
return;
}
setMatch(true);
data.username = data.username.toLowerCase();
axios
.post("http://localhost:5173/api/auth/signup", data, {
withCredentials: true,

View File

@@ -18,4 +18,8 @@ function sendMessage(message: string, recipient: string | null) {
function sendContact(recipient: string) {
socket.emit("contact", { recipient: recipient });
}
export { sendMessage, sendContact };
function sendRequestHistorical(recipient: string) {
socket.emit("historical", { recipient: recipient });
}
export { sendMessage, sendContact, sendRequestHistorical };

View File

@@ -1,6 +1,6 @@
const { Client } = require("pg");
const crypto = require("crypto");
require("dotenv").config();
const client = new Client({
user: process.env.PG_USER,
password: process.env.PG_PASSWORD,
@@ -47,6 +47,7 @@ async function createTables() {
recipient VARCHAR(128) NOT NULL,
message VARCHAR(500),
message_id SERIAL PRIMARY KEY
timestamp VARCHAR(100)
);
`);
} catch (e) {
@@ -64,7 +65,10 @@ async function createTables() {
}
}
async function insertUser(username, password, user_id, created_at) {
async function insertUser(username, password) {
const user_id = crypto.randomUUID();
const created_at = new Date().toLocaleString("pl-PL");
const query = `
INSERT INTO accounts (username, password, user_id, created_at)
VALUES ($1, $2, $3, $4);
@@ -77,13 +81,14 @@ async function insertUser(username, password, user_id, created_at) {
}
async function insertMessage(sender, recipient, message) {
const timestamp = new Date().toLocaleString("pl-PL");
const query = `
INSERT INTO messages (sender, recipient, message)
INSERT INTO messages (sender, recipient, message, timestamp)
VALUES ($1, $2, $3)
RETURNING message_id;
`;
try {
await client.query(query, [sender, recipient, message]);
await client.query(query, [sender, recipient, message, timestamp]);
} catch (e) {
console.error("Failed to insert message ", e);
}
@@ -91,11 +96,12 @@ async function insertMessage(sender, recipient, message) {
async function getMessages(username, recipient) {
const query = `
SELECT message FROM messages
SELECT message, timestamp FROM messages
WHERE (username = $1 AND recipient = $2);
`;
try {
await client.query(query, [username, recipient]);
const results = await client.query(query, [username, recipient]);
return results.rows[0];
} catch (e) {
console.error("Failed to get messages ", e);
}

View File

@@ -37,11 +37,9 @@ app.use(bodyParser.json());
app.use(cookieParser());
app.post("/api/auth/signup", async (req, res) => {
const username = req.body.username;
const username = req.body.username.toLowerCase();
const password = req.body.password;
const user_id = crypto.randomUUID();
const created_at = new Date();
console.log(username);
// Validate form data length
if (!username || username.length < 4 || username.length > 20) {
return res.status(400).json({ message: "Invalid username length" });

View File

@@ -10,6 +10,7 @@ function initializeSocket(io) {
const token = socket.handshake.auth.token;
const { username } = verifyJwtToken(token);
socket.join(username);
socket.on("chat message", (msg) => {
const { message, recipient } = msg;
@@ -20,6 +21,11 @@ function initializeSocket(io) {
insertMessage(username, recipient, message);
console.log("received from chat message", msg);
});
socket.on("historical", (recipient) => {
const messages = getMessages(username, recipient);
io.to(username).emit("historical", { messages });
});
socket.on("disconnect", () => {
console.log("User disconnected");
});