Skip to content

Instantly share code, notes, and snippets.

@jyotendra
Last active Aug 17, 2018
Embed
What would you like to do?
socket connection with middleware in node and angular
constructor() {
this.chats = [];
this.socket = io.connect(
baseUrl,
{
path: "/chat",
query: { "access-token": "---=====" },
reconnection: false
}
);
this.chats.push({
sent_by: this.sentByType.bot,
message: "hi",
time: new Date()
});
this.chats.push({
sent_by: this.sentByType.user,
message: "hello",
time: new Date()
});
}
ngOnInit() {
this.socket.on("error", err => {
console.log(">>>>>>>>>>", err);
switch (err) {
case "AUTH_FAILED":
console.log("authentication failed");
this.socket.disconnect(true);
break;
default:
break;
}
});
this.socket.on("disconnect", data => {
console.log("---------------", data);
});
}
// server side
export function attachEvents(io) {
ioConn = io;
io.use(async (socket, next) => {
const token = socket.handshake.query["access-token"];
const user = await validateUserToken(token).catch(err => {
next(new Error("AUTH_FAILED"));
});
socket.myUser = user;
return next();
});
ioConn.on("connection", socket => {
if (socket.myUser && socket.myUser.get("id")) socketStore[socket.myUser.get("id")] = socket;
});
ioConn.on("disconnect", socket => {
socket.disconnect(true);
if (socketStore[socket.myUser.get("id")]) delete socketStore[socket.myUser.get("id")];
});
}
// server side
const io = require("socket.io")(http, { path: "/chat" });
attachEvents(io);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment