const express = require('express'); const app = express(); require('dotenv').config(); // add dotnv for config const server = require('http').createServer(app); const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const User = require('./db/models/User'); const jwt = require('jsonwebtoken'); const PORT = process.env.PORT || 4000; const HASH_KEY = process.env.HASH_KEY; const TOKEN_KEY = process.env.TOKEN_KEY || 'rGH452fdfhdfg06hgj7'; const socket = require('socket.io'); const cors = require('cors'); app.get('/', (req, res) => { res.send('Hello from express server!') }) app.use(cors()); app.use(express.json()); const io = socket(server, { cors: { origin: "http://localhost:3000" //client endpoint and port } }); const generateToken = (id, userName) => { const payload = { id, userName, } return jwt.sign(payload, TOKEN_KEY); } const getOneUser = async (userName) => { return userInDb; } const user = getOneUser('Sergey'); io.on("connection", async (socket) => { console.log(socket.id); const userInDb = await User.findOne({userName: 'Sergey'}); socket.emit('connected', userInDb); }); const db = async () => { try{ const salt = await bcrypt.genSalt(2); const hashPassword = await bcrypt.hash('myPassword', salt); const user = new User({ userName: 'Sergey', hashPassword: hashPassword }) user.save(); }catch(e){ console.log(e) } } //db(); const start = async () => { try { await mongoose.connect('mongodb://localhost:27017/chat') .then(() => console.log(`DB started`)) server.listen(PORT, () => { console.log(`Server started. Port: ${PORT}`); }) } catch (e) { console.log(e); } } start();