devslopes-learn / mac-chat-api

Prebuilt api for slack app clone.
83 stars 87 forks source link

No channel gets created via Sockets #33

Open SumukhaK opened 3 years ago

SumukhaK commented 3 years ago

When I do this on my Kotlin Activity :

socket.emit("newChannel",channelName,channelDesc)

I don't see any channel getting created on mongo as shown in the tutorial. Nor any log on Heroku such as : new channel created . However I do get : a user connected at=info method=GET path="/socket.io/?EIO=4&transport=polling" host=herokumongodbsmackchat.herokuapp.com request_id=61a72504-c0ae-439f-9f75-228d3aae7a6b fwd="100.100.000.000" dyno=web.1 connect=1ms service=5ms status=200 bytes=328 protocol=https

Here's my index.js api code :

import http from 'http';
import express from 'express';
import bodyParser from 'body-parser';
import passport from 'passport';
import socket from 'socket.io';
import Message from './model/message';
import Channel from './model/channel';

const LocalStrategy  = require('passport-local').Strategy;

import config from './config';
import routes from './routes';

let app = express();
app.server = http.createServer(app);
let io = socket(app.server);

//middleware
//parse application/json
app.use(bodyParser.json({
  limit: config.bodyLimit
}));

//passport config
app.use(passport.initialize());
let Account = require('./model/account');
passport.use(new LocalStrategy({
  usernameField: 'email',
  passwordField: 'password'
},
  Account.authenticate()
));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());

//api routes v1
app.use('/v1', routes);

// Base URL test endpoint to see if API is running
app.get('/', (req, res) => {
  res.json({ message: 'Chat API is ALIVE!' })
});

/*||||||||||||||||SOCKET|||||||||||||||||||||||*/
//Listen for connection
var typingUsers = {};

io.on('connection', function(client) {
  console.log('a user connected');
  //Listens for a new chat message
  client.on('newChannel', function(name, description) {
    //Create channel
    let newChannel = new Channel({
    name: name,
    description: description,
  });
    //Save it to database
    newChannel.save(function(err, channel){
      //Send message to those connected in the room
      console.log('new channel created');
      io.emit("channelCreated", channel.name, channel.description, channel.id);
    });
  });

  //Listens for user typing.
  client.on("startType", function(userName, channelId){
    console.log("User " + userName + " is writing a message...");
    typingUsers[userName] = channelId;
    io.emit("userTypingUpdate", typingUsers, channelId);
  });

  client.on("stopType", function(userName){
    console.log("User " + userName + " has stopped writing a message...");
    delete typingUsers[userName];
    io.emit("userTypingUpdate", typingUsers);
  });

  //Listens for a new chat message
  client.on('newMessage', function(messageBody, userId, channelId, userName, userAvatar, userAvatarColor) {
    //Create message

    console.log(messageBody);

    let newMessage = new Message({
    messageBody: messageBody,
    userId: userId,
    channelId: channelId,
    userName: userName,
    userAvatar: userAvatar,
    userAvatarColor: userAvatarColor
  });
    //Save it to database
    newMessage.save(function(err, msg){
      //Send message to those connected in the room
      console.log('new message sent');

      io.emit("messageCreated",  msg.messageBody, msg.userId, msg.channelId, msg.userName, msg.userAvatar, msg.userAvatarColor, msg.id, msg.timeStamp);
    });
  });
});
/*||||||||||||||||||||END SOCKETS||||||||||||||||||*/

app.server.listen(config.port);
console.log(`Started on port ${app.server.address().port}`);

module.exports = {
  app,
  io
}

Edit-2 : I used a different library for Socket communication and I didn't send the proper parameters.

used : 'com.github.nkzawa:socket.io-client:0.6.0' . Rest of the steps are same as the one in the JohnnyB's tutorial

tromgy commented 3 years ago

console.log('new channel created') is only called from a database callback passed to newChannel.save.

You may want to check if your socket callback get invoked. Just add console.log('received newChannel message) just before

//Create channel
let newChannel = new Channel({

If you don't see "received newChannel message" in Heroku logs, then the problem is with your client. If you do see this message, but not "new channel created", the problem is on the server, and you need to find out why the callback on database save is not invoked.

SumukhaK commented 3 years ago

Thanks for the reply. I think I wasn't clear in my edit-2. I resolved the issue by myself. I don't know what the exact problem was, but once I changed the socket library I used in my kotlin code it worked but I received jibberish texts on channel name and description, but that was because I didn't pass the proper parameters while calling socket.emit from kotlin. So once I fixed my socket.emit, it worked just fine.