Commit e4d04c8a authored by Цой Данил's avatar Цой Данил 💬

Rewrote some logic on back and front of app

parent a2181d2b
## Так как запустил проект на простом react, запускается через npm start
\ No newline at end of file
APP_PORT=8000
PG_HOST=localhost
MONGO_CLIENT_URL=mongodb://localhost/TsoyDanilChatWS
ENV_SALT=10
SECRET_KEY=key
\ No newline at end of file
import * as path from "path";
import { dirname } from 'path';
import { fileURLToPath } from 'url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const rootPath = __dirname;
export default {
rootPath,
db: {
name: 'chat',
url: 'mongodb://localhost'
}
};
\ No newline at end of file
import mongoose from 'mongoose';
import express from "express";
import cors from 'cors';
import config from './config.js';
import expressWs from "express-ws";
import Users from './routes/Users.js';
import ChatWs from './routes/ChatWs.js';
import dotenv from 'dotenv'
dotenv.config()
const app = express();
const PORT = 8000;
expressWs(app);
app.use(cors());
......@@ -15,17 +15,20 @@ app.use(express.json());
app.use('/users', Users);
app.use('/chat', ChatWs);
const run = async() => {
mongoose.connect(`${config.db.url}/${config.db.name}`, {useNewUrlParser: true});
try{
mongoose.connect(process.env.MONGO_CLIENT_URL, {useNewUrlParser: true});
app.listen(PORT, () => {
console.log(`Server started at http://localhost:${PORT}/`);
app.listen(process.env.APP_PORT, () => {
console.log(`Server started at http://localhost:${process.env.APP_PORT}/`);
});
process.on("exit", () => {
mongoose.disconnect();
});
} catch(err){
console.log(err)
}
};
run().catch(console.error);
\ No newline at end of file
run()
\ No newline at end of file
......@@ -14,6 +14,7 @@ const MessageScheme = new Scheme({
},
datetime: {
type: Date,
required: false,
default: Date.now()
}
});
......
......@@ -11,11 +11,13 @@
"dependencies": {
"bcrypt": "^5.1.0",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"express-ws": "^5.0.2",
"mongoose": "^6.6.5",
"mongoose-sequence": "^5.3.1",
"nanoid": "^3.3.4"
"nanoid": "^3.3.4",
"shortid": "^2.2.16"
},
"devDependencies": {
"nodemon": "^2.0.20"
......@@ -488,6 +490,14 @@
"node": ">=8"
}
},
"node_modules/dotenv": {
"version": "16.0.3",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.0.3.tgz",
"integrity": "sha512-7GO6HghkA5fYG9TYnNxi14/7K9f5occMlp3zXAuSxn7CKCxt9xbNWG7yF8hTCSUchlfWSe3uLmlPfigevRItzQ==",
"engines": {
"node": ">=12"
}
},
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
......@@ -1588,6 +1598,19 @@
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="
},
"node_modules/shortid": {
"version": "2.2.16",
"resolved": "https://registry.npmjs.org/shortid/-/shortid-2.2.16.tgz",
"integrity": "sha512-Ugt+GIZqvGXCIItnsL+lvFJOiN7RYqlGy7QE41O3YC1xbNSeDGIRO7xg2JJXIAj1cAGnOeC1r7/T9pgrtQbv4g==",
"dependencies": {
"nanoid": "^2.1.0"
}
},
"node_modules/shortid/node_modules/nanoid": {
"version": "2.1.11",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-2.1.11.tgz",
"integrity": "sha512-s/snB+WGm6uwi0WjsZdaVcuf3KJXlfGl2LcxgwkEwJF0D/BWzVWAZW/XY4bFaiR7s0Jk3FPvlnepg1H1b1UwlA=="
},
"node_modules/side-channel": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz",
......@@ -2223,6 +2246,11 @@
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.1.tgz",
"integrity": "sha512-463v3ZeIrcWtdgIg6vI6XUncguvr2TnGl4SzDXinkt9mSLpBJKXT3mW6xT3VQdDN11+WVs29pgvivTc4Lp8v+w=="
},
"dotenv": {
"version": "16.0.3",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.0.3.tgz",
"integrity": "sha512-7GO6HghkA5fYG9TYnNxi14/7K9f5occMlp3zXAuSxn7CKCxt9xbNWG7yF8hTCSUchlfWSe3uLmlPfigevRItzQ=="
},
"ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
......@@ -3036,6 +3064,21 @@
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="
},
"shortid": {
"version": "2.2.16",
"resolved": "https://registry.npmjs.org/shortid/-/shortid-2.2.16.tgz",
"integrity": "sha512-Ugt+GIZqvGXCIItnsL+lvFJOiN7RYqlGy7QE41O3YC1xbNSeDGIRO7xg2JJXIAj1cAGnOeC1r7/T9pgrtQbv4g==",
"requires": {
"nanoid": "^2.1.0"
},
"dependencies": {
"nanoid": {
"version": "2.1.11",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-2.1.11.tgz",
"integrity": "sha512-s/snB+WGm6uwi0WjsZdaVcuf3KJXlfGl2LcxgwkEwJF0D/BWzVWAZW/XY4bFaiR7s0Jk3FPvlnepg1H1b1UwlA=="
}
}
},
"side-channel": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz",
......
......@@ -6,8 +6,8 @@
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js",
"dev": "nodemon server.js"
"start": "node index.js",
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
......@@ -18,10 +18,12 @@
"dependencies": {
"bcrypt": "^5.1.0",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"express-ws": "^5.0.2",
"mongoose": "^6.6.5",
"mongoose-sequence": "^5.3.1",
"nanoid": "^3.3.4"
"nanoid": "^3.3.4",
"shortid": "^2.2.16"
}
}
import express from 'express';
import expressWs from 'express-ws';
import { nanoid } from 'nanoid';
import User from '../models/User.js';
import Message from '../models/Message.js';
import shortid from 'shortid';
const router = express.Router();
expressWs(router);
......@@ -11,7 +11,7 @@ const activeConnections = {};
const users = [];
router.ws('/', (ws, req) => {
const id = nanoid();
const id = shortid.generate();
console.log(`Client connected id=${id}`);
activeConnections[id] = ws;
......@@ -35,12 +35,12 @@ router.ws('/', (ws, req) => {
});
break;
case 'CLOSED_CHAT':
const oflineUser = await User.find({_id: decodedMessage.user._id});
const offlineUser = await User.find({_id: decodedMessage.user._id});
Object.keys(activeConnections).forEach(connId => {
const conn = activeConnections[connId];
conn.send(JSON.stringify({
type: "CLOSED_CHAT_USER",
id: oflineUser[0]._id
id: offlineUser[0]._id
}));
});
break;
......
import express from 'express';
import User from '../models/User.js';
import shortid from 'shortid';
const router = express.Router();
router.post('/', async (req, res) => {
try{
const {username,password} = req.body;
const user = new User({
username,
password
username: req.body.username,
password: req.body.password
});
user.generateToken();
await user.save();
res.send(user);
}catch(error){
return res.status(400).send(error);
return res.status(418).send(error);
};
});
router.post('/sessions', async (req, res) => {
const user = await User.findOne({username: req.body.username});
if(!user) return res.status(400).send({error: 'User not found'});
if(!user) return res.status(418).send({error: 'User not found'});
const isMatch = await user.checkPassword(req.body.password);
if(!isMatch) return res.status(400).send({error: 'Password is wrong!'});
if(!isMatch) return res.status(418).send({error: 'Password is wrong!'});
return res.send(user);
});
......@@ -39,7 +39,7 @@ router.delete('/sessions', async (req, res) => {
if(!user) return res.send(successMessage);
user.token = nanoid();
user.token = shortid.generate();
await user.save({ validateBeforeSave: false });
return res.send(successMessage);
......
......@@ -4,21 +4,21 @@ import Message from '../Message/Message';
import './ChatWindow.css';
const ChatWindow = ({onSubmit, value, onChange, messages}) => {
const ChatWindow = (props) => {
return (
<div className='window'>
<div className='ChatWindow'>
<p className='ChatTitle'>Chat Room</p>
{
messages.map((message, idx) => {
props.messages.map((message, idx) => {
return (
<Message key={message?._id + idx} message={message?.message} author={message?.user.username || message.user}/>
)
})
}
</div>
<form onSubmit={onSubmit} className='formMessage'>
<input type="text" name="message" value={value} onChange={onChange}/>
<form onSubmit={props.onSubmit} className='formMessage'>
<input type="text" name="message" value={props.value} onChange={props.onChange}/>
<Button type='submit' className='sendMessageBtn' color="secondary" variant="text">Send</Button>
</form>
</div>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment