index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. const express = require('express');
  2. const app = express();
  3. require('dotenv').config(); // add dotnv for config
  4. const server = require('http').createServer(app);
  5. const mongoose = require('mongoose');
  6. const bcrypt = require('bcrypt');
  7. const User = require('./db/models/User');
  8. const jwt = require('jsonwebtoken');
  9. const PORT = process.env.PORT || 4000;
  10. const HASH_KEY = process.env.HASH_KEY;
  11. const TOKEN_KEY = process.env.TOKEN_KEY || 'rGH452fdfhdfg06hgj7';
  12. const socket = require('socket.io');
  13. const cors = require('cors');
  14. app.get('/', (req, res) => {
  15. res.send('Hello from express server!')
  16. })
  17. app.use(cors());
  18. app.use(express.json());
  19. const io = socket(server, {
  20. cors: {
  21. origin: "http://localhost:3000" //client endpoint and port
  22. }
  23. });
  24. const generateToken = (id, userName) => {
  25. const payload = {
  26. id,
  27. userName,
  28. }
  29. return jwt.sign(payload, TOKEN_KEY);
  30. }
  31. const getOneUser = async (userName) => {
  32. return userInDb;
  33. }
  34. const user = getOneUser('Sergey');
  35. io.on("connection", async (socket) => {
  36. console.log(socket.id);
  37. const userInDb = await User.findOne({userName: 'Sergey'});
  38. socket.emit('connected', userInDb);
  39. });
  40. const db = async () => {
  41. try{
  42. const salt = await bcrypt.genSalt(2);
  43. const hashPassword = await bcrypt.hash('myPassword', salt);
  44. const user = new User({
  45. userName: 'Sergey',
  46. hashPassword: hashPassword
  47. })
  48. user.save();
  49. }catch(e){
  50. console.log(e)
  51. }
  52. }
  53. //db();
  54. const start = async () => {
  55. try {
  56. await mongoose.connect('mongodb://localhost:27017/chat')
  57. .then(() => console.log(`DB started`))
  58. server.listen(PORT, () => {
  59. console.log(`Server started. Port: ${PORT}`);
  60. })
  61. } catch (e) {
  62. console.log(e);
  63. }
  64. }
  65. start();