Socket.io - shows an argument as "undefined" and randomly stops the app - javascript

I'm working on a simple chat app which was originally forked from a GitHub repo.
It works, but there's there's an error that randomly occurs and stops the app from running.
Server side code
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const formatMessage = require('./utils/messages');
const {
userJoin,
getCurrentUser,
userLeave,
getRoomUsers
} = require('./utils/users');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
const botName = 'CCBot';
v = process.env;
// Run when client connects
io.on('connection', socket => {
socket.on('joinRoom', ({ token, username, room }) => {
console.log(token, username, room)
if (token == v.TOKEN_1){username = v.N_1}
else if (token == v.TOKEN_2){username = v.N_2}
else if (token == v.TOKEN_3){username = v.N_3}
else{
socket.emit("redirect"); return
}
const user = userJoin(socket.id, username, room, token, false);
socket.join(user.room);
// Welcome current user
socket.emit('message', formatMessage(botName, 'Welcome!'));
// Broadcast when a user connects
socket.broadcast
.to(user.room)
.emit(
'message',
formatMessage(botName, `${user.username} has joined the chat!`, 'green')
);
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
});
// Listen for chatMessage
socket.on('chatMessage', (msg) => {
const user = getCurrentUser(socket.id)
console.log(user)
//The error originates on the below line
io.to(user.room).emit('message', formatMessage(user.username, msg, )); //The error occurs here
});
socket.on('userLeave', (id) => {
const user = getCurrentUser(id)
console.log(user)
socket.emit("sendMessages", user)
})
// Runs when client disconnects
socket.on('disconnect', () => {
const user = userLeave(socket.id);
if (user) {
io.to(user.room).emit(
'message',
formatMessage(botName, `${user.username} has left the chat.`, "red")
);
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
}
});
});
const PORT = process.env.PORT || 3000;
server.listen(300, () => console.log(`Server running on port 3000`));
Util functions
const users = [];
// Join user to chat
function userJoin(id, username, room, auth, admin ) {
const user = { id, username, room, admin };
users.push(user);
return user;
}
// Get current user
function getCurrentUser(id) {
return users.find(user => user.id === id);
}
// User leaves chat
function userLeave(id) {
const index = users.findIndex(user => user.id === id)
if (index !== -1) {
return users.splice(index, 1)[0];
}
}
// Get room users
function getRoomUsers(room) {
return users.filter(user => user.room === room);
}
module.exports = {
userJoin,
getCurrentUser,
userLeave,
getRoomUsers
};
function formatMessage(username, text, color) {
return {
username,
text,
time: moment().tz("My Timezone here.").format('h:mm a'),
color
};
}
module.exports = formatMessage;
Client Side
let notif = undefined;
// Get username and room from URL
const { username, room, token, t2 } = Qs.parse(location.search, {
ignoreQueryPrefix: true,
});
listUsers = [];
const socket = io();
// Join chatroom
socket.emit('joinRoom', { username, room, token });
// Get room and users
socket.on('roomUsers', ({ room, users }) => {
outputRoomName(room);
outputUsers(users);
});
socket.on("redirect", () => {
try { window.location = "wrongpassword.html" }
catch (e) {
window.location = "about:blank"
}
})
// Message from server
socket.on('message', (message) => {
console.log(message);
outputMessage(message);
// Scroll down
chatMessages.scrollTop = chatMessages.scrollHeight;
});
socket.on("sendMessages", user => {
banned.push(user.username)
socket.emit("BAN_ALERT")
})
// Message submit
chatForm.addEventListener('submit', (e) => {
e.preventDefault();
// Get message text
let msg = e.target.elements.msg.value;
msg = msg.trim();
if (!msg) {
return false;
}
// Emit message to server
socket.emit('chatMessage', msg);
// Clear input
e.target.elements.msg.value = '';
e.target.elements.msg.focus();
});
function enableNotif(){
notif = true;
}
function disableNotif(){
notif = false;
}
// Output message to DOM
function outputMessage(message) {
if (message.text == ".clear" || message.text ==
".c") {
try {
document.querySelector(".chat-messages").innerHTML = ""
return
}
catch (e) {
window.location.reload(true)
return
}
}
else if (message.text == ".exit" || message.text == ".e"){
location = "about:blank"
}
else if (message.text == ".users"){
console.log(userList)
div = document.createElement('div');
div.classList.add('message');
const p = document.createElement('p');
p.classList.add('meta');
p.innerText = "CCBot";
p.innerHTML += ` <span>${message.time}</span>`;
div.appendChild(p);
const para = document.createElement('p');
para.classList.add('text');
para.innerText = listUsers;
color = "black";
if(color){para.style.color = color}
else{para.style.color = "black"}
div.appendChild(para);
document.querySelector('.chat-messages').appendChild(div);
}
else {
const div = document.createElement('div');
div.classList.add('message');
const p = document.createElement('p');
p.classList.add('meta');
p.innerText = message.username;
p.innerHTML += ` <span>${message.time}</span>`;
div.appendChild(p);
const para = document.createElement('p');
para.classList.add('text');
para.innerText = message.text;
color = message.color;
if(color){para.style.color = color}
else{para.style.color = "black"}
div.appendChild(para);
document.querySelector('.chat-messages').appendChild(div);
if (notif) {
var audio = new Audio('./media/notif.mp3');
console.log(audio)
audio.play();
}
}
}
// Add room name to DOM
function outputRoomName(room) {
roomName.innerText = room;
}
// Add users to DOM
function outputUsers(users) {
userList.innerHTML = '';
users.forEach((user) => {
const li = document.createElement('li');
li.innerHTML = `${user.username} <br><hr>`;
li.style = "cursor:pointer;"
userList.appendChild(li);
listUsers.push(li.innerText)
});
}
//Prompt the user before leave chat room
document.getElementById('leave-btn').addEventListener('click', () => {
const leaveRoom = confirm('Are you sure you want to leave the chatroom?');
if (leaveRoom) {
window.location = '../index.html';
} else {
}
});
Error
TypeError: Cannot read property 'room' of undefined
at Socket.socket.on.msg (/home/duck/server.js:51:16)
at Socket.emit (events.js:198:13)
at /home/duck/node_modules/socket.io/lib/socket.js:528:12
at process._tickCallback (internal/process/next_tick.js:61:11)
/home/duck/server.js:51
io.to(user.room).emit('message', formatMessage(user.username, msg));
^
The repo already has this issue opened, but there's no response to it.
I'm not sure why the error occurs.
Thanks in advance.
P.S, Please ignore anything related to banning/removing users.

Related

ReferenceError: window is not defined in agora-rtc-sdk-ng in node js

What I want to do
I want manually add users to the channel from the backend(node js) using agora SDK.
Error
I am getting ReferenceError: window is not defined while implementing Agora-Rtc-SDK in Node js
https://prnt.sc/52Dp_D9-gwEu
I tried agora-rtc-SDK-ng and agora-rtc-sdk both libraries but I am getting the same error.
Here is What I did
First I generate token using agora-access-token then after using that token I join the particular channel
Code
const cors = require('cors');
const dotenv = require('dotenv');
const AgoraRTC = require('agora-rtc-sdk-ng')
const {RtcTokenBuilder, RtcRole } = require('agora-access-token');
dotenv.config();
const app = express();
const PORT = process.env.PORT || 8080;
const APP_ID = process.env.APP_ID;
const APP_CERTIFICATE = process.env.APP_CERTIFICATE;
const generateRTCToken = (req, resp) => {
const channelName = req.params.channel;
let uid = req.params.uid;
// get role
let role;
if (req.params.role === 'publisher') {
role = RtcRole.PUBLISHER;
} else if (req.params.role === 'audience') {
role = RtcRole.SUBSCRIBER
} else {
return resp.status(500).json({ 'error': 'role is incorrect' });
}
// get the expire time
let expireTime = req.query.expiry;
if (!expireTime || expireTime === '') {
expireTime = 3600;
} else {
expireTime = parseInt(expireTime, 10);
}
// calculate privilege expire time
const currentTime = Math.floor(Date.now() / 1000);
const privilegeExpireTime = currentTime + expireTime;
// build the token
let token;
if (req.params.tokentype === 'userAccount') {
token = RtcTokenBuilder.buildTokenWithAccount(APP_ID, APP_CERTIFICATE, channelName, uid, role, privilegeExpireTime);
} else if (req.params.tokentype === 'uid') {
token = RtcTokenBuilder.buildTokenWithUid(APP_ID, APP_CERTIFICATE, channelName, uid, role, privilegeExpireTime);
} else {
return resp.status(500).json({ 'error': 'token type is invalid' });
}
// return the token
return token;
}
const addUserToChannle = async () => {
const client = AgoraRTC.createClient({
codec: "vp8",
mode: "rtc",
});
let token = await generateRTCToken()
client.join(APP_ID, req.params.channel, token);
}
app.get('/rtc/:channel/:role/:tokentype/:uid', nocache , addUserToChannle);
app.listen(PORT, () => {
console.log(`Listening on port: ${PORT}`);
});
[1]: https://prnt.sc/52Dp_D9-gwEu

How would I loop through a json file?

I'm making a verification system where people link their accounts on two different platforms. I've got the code working, but now I need to check if the code is valid. I'm using .forEach on the json file, yet I keep getting the error:
client.verificationCodes.forEach is not a function
and it crashes.
Here is what the json file looks like:
my json file
Here is my code:
const Discord = require('discord.js')
const rbx = require('noblox.js')
const fs = require("fs")
const express = require("express")
const app = express()
app.use(express.json())
const client = new Discord.Client()
client.verificationCodes = require("./codes.json")
require("dotenv").config()
const port = process.env.PORT
const serverKey = process.env.SERVER_KEY
const cookie = process.env.COOKIE
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
client.on("ready", () => {
console.log("Client is ready.")
})
app.post("/getVerificationCode", function(req,res,next) {
console.log("Recieved")
if (req.body.serverKey !== serverKey) {
console.log("Invalid serverKey supplied.")
return res.status(403).json({
error: "You do not have permission to use this."
})
}
let verificationCode = randomString(4,'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').toUpperCase()
const userID = parseInt(req.body.userid)
console.log(verificationCode)
client.verificationCodes[userID] = {
code: verificationCode
}
fs.writeFile("./codes.json", JSON.stringify(client.verificationCodes,null,4), err => {
if (err) throw err
})
return res.status(200).json({
VerificationCode: verificationCode
})
})
app.get("/*", function(req,res,next) {
return res.status(200).json({})
})
client.on("message", (message) => {
if (message.content.toLowerCase().startsWith("!verify")) {
let args = message.content.split(" ")
if (!args[1]) {
message.reply("You must specify a code.")
return
}
client.verificationCodes.forEach(vCode => {
if (vCode.Code === args[1]) {
let username = rbx.getUsernameFromId(vCode)
message.member.setNickname(username)
}
})
}
})
app.listen(port)
console.log(`App listening on port ${port}`)
function rbxLogin(newCookie) {
try {
rbx.setCookie(newCookie)
} catch(err) {
console.log(`Invalid cookie supplied, or expired. ${err}`)
}
}
// rbxLogin(cookie)
client.login(process.env.BOT_TOKEN)
I appreciate help!
You had a syntax error because .forEach doesn't work on objects but on array and since that client.verificationCodes is an object then you need to use Object.entries to convert that to array of key, value.
I've refactored the block causing this error please use this:
Object.entries(client.verificationCodes).forEach(([key, vCode]) => {
if (vCode.Code === args[1]) {
let username = rbx.getUsernameFromId(vCode)
message.member.setNickname(username)
}
})
which will make your whole code like this:
const Discord = require('discord.js')
const rbx = require('noblox.js')
const fs = require("fs")
const express = require("express")
const app = express()
app.use(express.json())
const client = new Discord.Client()
client.verificationCodes = require("./codes.json")
require("dotenv").config()
const port = process.env.PORT
const serverKey = process.env.SERVER_KEY
const cookie = process.env.COOKIE
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
client.on("ready", () => {
console.log("Client is ready.")
})
app.post("/getVerificationCode", function(req,res,next) {
console.log("Recieved")
if (req.body.serverKey !== serverKey) {
console.log("Invalid serverKey supplied.")
return res.status(403).json({
error: "You do not have permission to use this."
})
}
let verificationCode = randomString(4,'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').toUpperCase()
const userID = parseInt(req.body.userid)
console.log(verificationCode)
client.verificationCodes[userID] = {
code: verificationCode
}
fs.writeFile("./codes.json", JSON.stringify(client.verificationCodes,null,4), err => {
if (err) throw err
})
return res.status(200).json({
VerificationCode: verificationCode
})
})
app.get("/*", function(req,res,next) {
return res.status(200).json({})
})
client.on("message", (message) => {
if (message.content.toLowerCase().startsWith("!verify")) {
let args = message.content.split(" ")
if (!args[1]) {
message.reply("You must specify a code.")
return
}
Object.entries(client.verificationCodes).forEach(([key, vCode]) => {
if (vCode.Code === args[1]) {
let username = rbx.getUsernameFromId(vCode)
message.member.setNickname(username)
}
})
}
})
app.listen(port)
console.log(`App listening on port ${port}`)
function rbxLogin(newCookie) {
try {
rbx.setCookie(newCookie)
} catch(err) {
console.log(`Invalid cookie supplied, or expired. ${err}`)
}
}
// rbxLogin(cookie)
client.login(process.env.BOT_TOKEN)

Chunks of code being ignored. No errors, no logs. Might be API related

The code below doesn't give any errors but I have a weird bug anyway. I have four streams to aggregate twitter feeds to a discord channel. 3 of those often work. but whenever I run the code there is always a feed not coming through, no line is getting executed in that stream. This often happens with the IntelFeed and/or covid-19feed. When I wait for some time or repeatedly rerun the code it starts working. I think it may be due to the structure of the code (not having enough time to fulfill the conditions) or due to the API. But I can't confirm the latter one.
const Discord = require('discord.js');
const botconfig = require("./botconfig.json");
const { Client, RichEmbed } = require('discord.js');
const twitterFeedsModel = require('./models/twitterFeedsModel');
const client = new Discord.Client();
const mongoose = require('mongoose', {useNewUrlParser: true}, { useUnifiedTopology: true });
mongoose.connect('mongodb://localhost/twitterFeedDatabeses');
const Twit = require('twit');
const T = new Twit({
consumer_key: botconfig.consumer_key,
consumer_secret: botconfig.consumer_key_secret,
access_token: botconfig.access_token,
access_token_secret: botconfig.access_token_secret,
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
//Newsfeed
const stream = T.stream("statuses/filter", { follow: ["5402612", "1652541", "831470472", "26792275", "380648579", "426802833", "144274618", "31696962", "1642135962", "16561457"]});
const scr_name = ['BBCbreaking', 'Reuters', 'pewglobal', 'ForeignPolicy', 'AFP', 'AP_Politics', 'economics', 'dw_europe', 'BBCNewsAsia', 'RadioFreeAsia']
stream.on("tweet", function (tweet) {
if(!scr_name.includes(tweet.user.screen_name)) return;
client.channels.get("646745474514026506").send(`https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`);
});
//Covid-19stream
const secondStream = T.stream("statuses/filter", {follow: "2985479932"});
const secondScr_name = "BNODesk"
secondStream.on("tweet", function (tweet){
console.log(tweet.user.screen_name)
if(secondScr_name.includes(tweet.user.screen_name)) {
const tweetContent = tweet.text.split(" ");
console.log(tweetContent)
const filteredWords = ['thank', 'Thank', 'you', 'you.', 'you!']
console.log("It does include Breakin: " + tweetContent.includes("BREAKING:"))
if(!filteredWords.some(word => tweet.text.includes(word))){
if(tweetContent.includes("BREAKING:")){
console.log("It does include breaking (after if-statement): " + tweetContent.includes("BREAKING:"))
client.channels.get("645733080061181965").send(`https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`)
client.channels.get('645733080061181965').send('I found out this tweet covers important news')
} else if(!tweet.text.startsWith("#")){
client.channels.get("645733080061181965").send(`https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`)
client.channels.get("645733080061181965").send(`Hello <#283206528004259850>, there is a new tweet!`)
}
}
}
});
//GRUNNstream
const thirdStream = T.stream("statuses/filter", { follow: ["14907733", "22465767", "18549902", "451432440", "97639259", "2343981858"]});
const thirdScr_name = ['rtvnoord', 'oogtv', 'dvhn_nl', 'P2000Groningen', 'polgroningen', 'Sikkom050']
thirdStream.on("tweet", function (tweet) {
if(thirdScr_name.includes(tweet.user.screen_name)) {
client.channels.get("632705489108729867").send(`https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`);
}
});
// intelstream
const fourthStream = T.stream("statuses/filter", {follow: ['3331851939', '2407993940', '1140336427550552000', '2790057867', '2315512764', '1517300821', '70529694', '62248461', '146958450', '85904241', '762565517026664400']});
const fourthScr_name = ['IntelCrab', 'IntelDoge', 'IntelAgencyNGO', 'lummideast', 'bellingcat', 'obretix', 'JanesINTEL', 'BarzanSadiq', 'ragipsoyly', 'leventkemal', 'OmerOzkizilcik']
fourthStream.on("tweet", function (tweet) {
if(fourthScr_name.includes(tweet.user.screen_name)) {
client.channels.get("646745512011235339").send(`https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`);
}
});
});
module.exports.run = client.on('message', message => {
if (!message.content.startsWith(botconfig.prefix) || message.author.bot) return;
const args = message.content.slice(botconfig.prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command.length === 0) {
return message.channel.send(`I ain't gonna fill the command in by myself fam`);
}
if (command === 'add_twitter_feed'){
if (!args.length){
return message.channel.send("Please enter a valid value!")};
var twitterUsername_feed = args;
T.get('users/show', { screen_name: twitterUsername_feed.join() }, function (err, data, response) {
console.log(data.id)
const twitterFeedVar = new twitterFeedsModel({
_id: mongoose.Types.ObjectId(),
twitterUsernameAddedToFeed: twitterUsername_feed.join(),
twitterUsername_idAddedToFeed: data.id,
})
twitterFeedVar.save()
.then(result => console.log(result))
.catch(err => console.log(err))
twitterFeedVar.find()
.then(doc => {
message.channel.send(doc)
})
})
}
/*if (command === `savelist`) {
Test.find()
.then(doc => {
message.channel.send(doc)
})
}
*/
if (command === 'twitter_user_id'){
if (!args.length){
return message.channel.send("Please enter a valid value!")};
var twitterUsername_lookup = args;
console.log(`${message.member.user.tag} requested the ID of the following user: ` + twitterUsername_lookup.join())
T.get('users/show', { screen_name: twitterUsername_lookup.join() }, function (err, data, response) {
console.log(data)
message.channel.send(`This is the ID of ` + twitterUsername_lookup.join() + `: ` + data.id)
if (!data.id) {
return message.channel.send(`Twitter user not found.`)
}
})
message.delete()
}
if (command === `hello`){
return message.channel.send("Hi there :)")
}
if (command === `feedlist`){
var scr_name2 = ['BBCbreaking', 'Reuters', 'pewglobal', 'ForeignPolicy', 'AFP', 'AP_Politics', 'economics', 'dw_europe', 'BBCNewsAsia', 'RadioFreeAsia']
return message.channel.send(scr_name2)
}
if (command === `reload`) {
message.channel.send(`Reloading...`)
console.clear();
client.destroy()
client.login(botconfig.token);
message.channel.send(`Bot reloaded succesfully!`);
return;
}
});
module.exports.help = {
name: "testtest"
}
client.login(botconfig.token);

How to disconnect a client for being inactive in chat for a specific time (socket.io, javascript)

In this chat app I want the server to disconnect clients who's been inactive for x (configurable) amount of time.
I think the default is 60 sec, I think I should use page Timeout as you can see in my server file but not sure how to make it work.
The idea is to have a timer for let's say 2 minutes of inactivity and you get kicked out with a message appearing afterwards in the feedbackBox function in name.js file.
My code is below:
server.js
const PORT = 3000;
const io = require('socket.io')(PORT, {
pingTimeout: 60000
});
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
const users = {};
io.on('connection', socket => {
socket.on('new-user', name => {
if (Object.values(users).includes(name)) {
socket.emit('name-taken', name);
}
if (!Object.values(users).includes(name)) {
users[socket.id] = name;
socket.emit('user-accepted');
socket.broadcast.emit('user-connected', name);
}
});
socket.on('send-chat-message', message => {
socket.broadcast.emit('chat-message', {
message: message,
name: users[socket.id]
});
});
socket.on('disconnect', reason => {
socket.broadcast.emit('user-disconnected', users[socket.id]);
delete users[socket.id];
});
});
name.js
const container = document.querySelector('.container');
const nameContainer = document.createElement('section');
const title = document.createElement('h1');
const form = document.createElement('form');
const nameInput = document.createElement('input');
const submitName = document.createElement('button');
title.innerText = 'Enter Your Name';
submitName.innerText = 'Connect';
const getName = () => {
form.addEventListener('submit', e => {
e.preventDefault();
const name = nameInput.value;
socket.emit('new-user', name);
nameInput.value = '';
socket.off('name-taken');
socket.on('name-taken', () => {
feedbackBox('Nickname already taken');
});
socket.off('user-accepted');
socket.on('user-accepted', () => {
title.classList.add('hide');
nameContainer.classList.add('hide');
addMessageForm();
});
});
};
const appendForm = () => {
nameInput.classList.add('name_input');
form.appendChild(nameInput);
submitName.classList.add('submit_name');
form.appendChild(submitName);
nameContainer.appendChild(form);
nameContainer.classList.add('name_container');
nameContainer.classList.remove('hide');
title.classList.remove('hide');
title.classList.add('name_title');
container.appendChild(title);
container.appendChild(nameContainer);
getName();
};
chat.js
//const socket = io('http://localhost:3000');
const showFeedback = document.createElement('section');
const messageContainer = document.createElement('section');
const messageForm = document.createElement('form');
const messageInput = document.createElement('input');
const submitMessage = document.createElement('button');
const disconnectButton = document.createElement('button');
submitMessage.innerText = 'Send';
disconnectButton.innerText = 'X';
messageContainer.classList.add('message-container');
messageForm.classList.add('send-container');
messageInput.classList.add('message-input');
submitMessage.classList.add('send-button');
disconnectButton.classList.add('disconnect-button');
const addMessageForm = () => {
showFeedback.classList.add('hide');
messageContainer.classList.remove('hide');
messageForm.classList.remove('hide');
disconnectButton.classList.remove('hide');
messageForm.appendChild(messageInput);
messageForm.appendChild(submitMessage);
container.appendChild(disconnectButton);
container.appendChild(messageContainer);
container.appendChild(messageForm);
appendMessage('You joined');
};
//const name = prompt('What is your name?');
//socket.emit('new-user', name);
socket.on('chat-message', data => {
appendMessage(`${data.name}: ${data.message}`);
});
socket.on('user-connected', name => {
appendMessage(`${name} connected`);
});
socket.on('user-disconnected', name => {
appendMessage(`${name} left the chat`);
});
messageForm.addEventListener('submit', e => {
e.preventDefault();
const message = messageInput.value;
appendMessage(`You: ${message}`);
socket.emit('send-chat-message', message);
messageInput.value = '';
});
function appendMessage(message) {
const messageElement = document.createElement('section');
messageElement.innerText = message;
messageContainer.append(messageElement);
}
const feedbackBox = message => {
showFeedback.innerText = message;
showFeedback.classList.add('feedback-I-disconnect');
showFeedback.classList.remove('hide');
container.appendChild(showFeedback);
};
disconnectButton.addEventListener('click', event => {
if (event.target.classList.contains('disconnect-button')) {
socket.disconnect();
messageContainer.classList.add('hide');
messageForm.classList.add('hide');
disconnectButton.classList.add('hide');
appendForm();
feedbackBox('You disconnected from the chat');
}
});
You could set a timeout on the socket and clear the timeout every time you receive a message from that client:
socket.on("sent-chat-message", message => {
clearTimeout(socket.inactivityTimeout);
socket.inactivityTimeout = setTimeout(() => socket.disconnect(true), 1000 * 60);
});
I'm not sure if the connection will be re-established automatically, in which case you'd have to do this on the client-side as well.

Getting TypeError: FabricUserControllers is not a constructor which can not be catch

I am new to node.js and Javascript.
I have two javascript files "FabricUserController.js" and "UserController.js". So I have create the class in "FabricUserController.js" and export it into "UserController.js".
I am integrate the GetAll fucntion of "FabricUserController.js" to "UserController.js" in GetAllProduce fucntion.
I am trying run the below code however its giving me "TypeError: FabricUserControllers is not a constructor" error which is not handle in try catch{} block
Please see below code
let FabricUserControllers3 = require("./FabricUserController");
GetAllProduce: function (req, res, next) {
try{
let output = {};
var resArray = new Array();
let VZID = req.body.username;
console.log('test', 'GetAllProduce')
console.log('USername', VZID)
MongoClient.connect(config.Database.TEST.connectString, function (err, client) {
if (err) {
let connError = new Error(500, "Error connecting to TEST database", err);
res.status(connError.status).json(connError);
} else {
let query = {};
client.db(config.Database.TEST.dbName).collection("Produce").find(query).toArray(function (err, response) {
console.log(response);
if (err) {
let roleError = new Error(500, "Error getting Produce information", err);
res.status(500).json(roleError);
} else if (response.length > 0) {
//DO someting here
//FabricUserControllers3 = {};
FabricUserControllers3 = new FabricUserControllers();// getting issue here
FabricUserControllers3.GetAll((VZID), (response) => {
console.log("data result", result)
res.status(200).json(response);
client.close();
})
} else {
output.message = "Produce doesn't exist";
res.status(409).json(output);
client.close();
}
});
}
});
}catch(e){
if (e instanceof TypeError){
console.log('error1', e.message);
printError(e,true);
}else{
console.log("error2", e.message);
printError(e, false);
}
}
},
FabricUserController.js
'use strict';
const {
FileSystemWallet,
Gateway
} = require('fabric-network');
const fs = require('fs');
const path = require('path');
var MongoClient = require('mongodb').MongoClient;
var Client = require('node-rest-client').Client;
var client = new Client();
const configPath = path.resolve(__dirname, '..', 'config', 'Config.json');
const configJSON = fs.readFileSync(configPath, 'utf8');
const config1 = JSON.parse(configJSON);
var connection_file = config1.connection_file;
var appAdmin = config1.appAdmin;
var gatewayDiscovery = config1.gatewayDiscovery;
var appAdminSecret = config1.appAdminSecret;
var orgMSPID = config1.orgMSPID;
var caName = config1.caName;
const ccpPath = path.resolve(__dirname, '..', 'config', 'connection.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
let response = {};
class FabricUserControllers {
constructor() {
console.log("constructer called")
}
async ProduceRegistration(Username, produceid, callback) {
// Create a new file system based wallet for managing identities.
try {
const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {
setTimeout(() => {
cb();
resolve();
}, timeout);
});
let query2 = {}
query2.PRODUCEID = produceid;
// console.log('PRODUCEID',produceid)
var PRODUCE = {};
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
console.log('Username', Username)
// Check to see if we've already enrolled the user.
const userExists = await wallet.exists(Username);
if (!userExists) {
console.log('An identity for the user: ' + Username + ' does not exist in the wallet');
console.log('call the registerUser before retrying');
response.data = null;
response.httpstatus = 400;
response.message = `An identity for the ${Username} does not exist in the wallet`;
return response;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccpPath, {
wallet,
identity: Username,
discovery: {
enabled: false,
asLocalhost: true
}
});
///
MongoClient.connect(config.Database.TEST.connectString, function (err, client) {
if (err) {
// let connError = new Error(500, "Error connecting to TEST database", err);
response.data=null;
response.httpstatus = 500;
response.message = "Error connecting to TEST database :" + err;
// res.status(connError.status).json(connError);
return response;
} else {
client.db(config.Database.TEST.dbName).collection("Produce").find(query2).toArray(function (err, docs) {
if (err) {
response.httpstatus = 500;
response.message = "Error with DB :" + err;
return response;
}
else{
console.log("blockchain_status", docs[0].blockchain_status)
console.log('Role name DB',docs);
console.log('Role name DB1',docs[0]);
if(docs[0].STATUS)
PRODUCE.produceid = docs[0].PRODUCEID;
PRODUCE.produceName = docs[0].PRODUCE;
PRODUCE.farmLocation = docs[0].FARMLOCATION;
PRODUCE.plantingDate = docs[0].PLANTINGDATE;
PRODUCE.harvestDate = docs[0].HARVESTDATE;
PRODUCE.status = docs[0].STATUS;
PRODUCE.produceQuantites = docs[0].VARIETY;
PRODUCE.gapInfo = docs[0].GAP;
PRODUCE.farmerID = docs[0].farmerID;
console.log('Produce', PRODUCE);
const doStuffAsync = async () => {
setAsyncTimeout(async () => {
// Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('dfarmchannel');
// Get the contract from the network.
const contract = network.getContract(config1.chaincodeName);
var args = JSON.stringify(PRODUCE)
console.log("type of arg", typeof (args));
// Submit the specified transaction.
// console.log('produceID', args.produceID);
if(args==null || args==''){
console.log('Server not responding please try again');
}else
{
const result = await contract.submitTransaction('ProduceRegistration', args);
var argsJson = JSON.parse(result)
// console.log('result', argsJson)
// console.log('result1', result)
if(argsJson.produceID !="" && argsJson.produceID !=null && argsJson.produceID !="undefined" && argsJson.produceID !=undefined){
// // return false;
response.data = result
response.httpstatus = 200;
response.message = `Transaction has been submitted ansd successfull with Result :${result}`;
return callback(response);
// console.log('result before', response);
// console.log('Transaction has been submitted ansd successfull with Result :' + result);
}else{
console.log('blockchain server not responed')
// return false
response.httpstatus = 500;
response.message = `Please enter produce ID :`;
return response;
}
}
}, 4000);
};
doStuffAsync();
}
client.close();
})
}
})
await gateway.disconnect();
}
catch (error) {
// if(error) throw error;
response.error = error;
response.httpstatus = 500;
response.message = "Failed to enroll admin due to above error";
return response;
}
};
}
module.exports = FabricUserControllers;
#Abhirock, on your main file you have:
let FabricUserControllers3 = require("./FabricUserController");
FabricUserControllers3 = new FabricUserControllers();// getting issue here
You are trying to override FabricUserControllers3 creating a new object FabricUserControllers but you are not importing it. Try next solution to see if it solves your problem:
const FabricUserController = require("./FabricUserController");
const fabricUserControllers3 = new FabricUserController();
Hope it helps :))

Categories

Resources