Socket.io a particular event emit is not working - javascript

I have backend in nodejs and frontend in Reactjs, I am using socket.io for live event handling, everything works fine apart from one thing. I am attaching my server and client code snippets here :
server.js
socket.on("joinroom", ({ roomid, username }, callback) => {
console.log("student joined room", username);
socket.join(roomid);
socket.to(roomid).emit("newstudentcount");
socket.to(roomid).emit("scoreupdate");
socket.to(roomid).emit("info", { username, roomid });
});
and for client react application:
componentDidMount() {
socket = io("http://127.0.0.1:5000");
socket.emit("joinroom", {
username: this.props.userData.username,
roomid: this.props.roomInfo.roomid,
});
socket.on("scoreupdate", () => {
console.log("order to get score")
this.getMyScore();
})
socket.on("newpuzzle", ({ config, min, sec }) => {
console.log("TEACHER GAVE ME NEW PUZZLE");
console.log(config, min, sec);
this.setState({
puzConfig: config,
time: this.calculateSeconds(min,sec),
totalTIme: this.calculateSeconds(min,sec),
isPuzAssign: true,
});
this.startTimer();
});
}
every other event emits work fine apart from scoreupdate event. Now I am not sure what is wrong here, either the client is unable to read the event or the server is not emitting the event. In either case, I don't see any issue in this code.
Things I have already tried:
changing event name
changing sequence of events
removing other events apart from scoreupdate.
Nothing works.
It would be great if someone could help.

Related

onMessage event is not triggered when agent sends a message amazon-connect-chatjs

I'm integrating amazon connect chatbot on my end and I want to establish a connection between a customer and an agent. In order to so, I have used onMessage event to retrieve agent messages back on my platform but right now, it is not triggered.
I have initially used aws-sdk and #aws-sdk/client-connectparticipant library to send messages where I have used multiple SDKs api in this order
startChatContact -> createParticipantConnection -> sendEvent -> sendMessage
This was done in order to establish a connection between a client and an agent, so that they can send messages to each other as well. With these SDKs, I was successfully able to send messages from customer to agent but in order to retrieve the messages back, I have used getTranscript api inititally, which I was calling in every 2 seconds to check for any updated messages. I have also stored message ids on my end to avoid any duplicate entries.
But now I'm looking for a better solution and for that, I have used amazon-connect-chatjs library and I have used the code below:
import "amazon-connect-streams";
import "amazon-connect-chatjs";
connect.contact(contact => {
if (contact.getType() !== connect.ContactType.CHAT) {
// applies only to CHAT contacts
return;
}
contact.onAccepted(() => {
const cnn = contact.getConnections().find(cnn => cnn.getType() === connect.ConnectionType.AGENT);
const agentChatSession = connect.ChatSession.create({
chatDetails: cnn.getMediaInfo(),
options: {
region: "us-west-2"
},
type: connect.ChatSession.SessionTypes.AGENT,
websocketManager: connect.core.getWebSocketManager()
});
});
});
I have also tried creating a customer chat session, but it is not working as well
const customerChatSession = connect.ChatSession.create({
chatDetails: {
contactId: "...",
participantId: "...",
participantToken: "..."
},
options: { // optional
region: "us-west-2"
},
type: connect.ChatSession.SessionTypes.CUSTOMER
});
Apart from that, I have used onTyping event, but it is not getting triggered as well.
Please let me know if I'm missing anything or doing anything wrong here.
Update1
if i add console.log
const customerChatSession = connect.ChatSession.create({
chatDetails: {
contactId: "...",
participantId: "...",
participantToken: "..."
},
options: { // optional
region: "us-west-2"
},
type: connect.ChatSession.SessionTypes.CUSTOMER
});
console.log("Here");
then even it does not print Here.
There is no error on console.
To create agentChatSession need websocket
connect.core.getWebSocketManager()
this is undefined even.

Posting result data to a website (like API or a telegram bot) after a test on Cypress

I've finished writing my first Cypress test. Everything is good except I'm struggling to post the result data to a website. Because I want to send the result data and also if any errors occurs the result screenshot to our coworker telegram group.
For the last two days I've tried everything and couldn't find any solution.
I've tried those in my test script (cypress/integration/test.js);
Cypress.on('test:after:run', (test, runnable) => {
console.log('test,runnable', test, runnable)
const details = {
projectKey: Cypress.env('zephyr-project-key'),
testName: test.invocationDetails.relativeFile,
status: test.status,
error: runnable.err.message,
retries: runnable.retries.length,
duration: test.wallClockDuration,
startTime: test.wallClockStartedAt
}
cy.request('POST', 'http://mywebsite.com/notify.php', { body: details })
fetch('http://mywebsite.com/notify.php')
})
Also this didn't work (cypress/plugins/index.js);
module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
on('after:run', (results) => {
if (results) {
// results will be undefined in interactive mode
console.log(results.totalPassed, 'out of', results.totalTests, 'passed')
fetch('http://mywebsite.com/notify.php');
}
})
}
Edit: This is day 3 and I still couldn't solve this. What I've seen from Cypress help page is that cy.task() calls do not fire in 'test:after:run' event block;
https://github.com/cypress-io/cypress/issues/4823
I've seen some telegram groups who can do what I'm trying to do. All I need is to be able to get the results and post it to my website.
The third parameter to cy.request() is body, you don't have to wrap it.
Cypress.on('test:after:run', (test, runnable) => {
const details = {
projectKey: Cypress.env('zephyr-project-key'),
testName: test.invocationDetails.relativeFile,
status: test.status,
error: runnable.err?.message, // need err?.message if there is no error
retries: runnable.retries.length,
duration: test.wallClockDuration,
startTime: test.wallClockStartedAt
}
cy.request('POST', 'http://mywebsite.com/notify.php', details) // don't wrap details
.then(res => expect(res.status).to.eq(201)) // confirm result
})

Braintree Node.js cannot get transaction.sale to work

I am building a reactjs app that among others will include Braintree Dropin UI integration. So far, I have managed to make the UI show up and send a payload to the back end. However, I cannot get the gateway.transaction.sale() part to work. Here is my code's relevant parts:
When the user clicks the pay button, this is fired:
instance.requestPaymentMethod().then(function (payload) {
console.log(payload);
completePayment(amount, payload.nonce, userId, sessionId).then((result) => {
console.log( result );
});
}).catch(function (err) {
alert(err.message);
});
And this is the code that should handle the transaction:
return gateway.transaction.sale({
amount: amount,
paymentMethodNonce: nonce,
customFields: {
session_id: sessionId,
user_id: userId
},
options: {
submitForSettlement: true
}
}).then(function (result) {
if (result.success) {
console.log('Transaction ID: ' + result.transaction.id);
} else {
console.error(result.message);
}
}).catch(( error ) => {
alert(error);
});
Every time this function is fired, I get this error from catch:
TypeError: can't assign to property "success" on :not an object
Can anyone point me in the right direction?
Please note that I am not very familiar with react, node etc so my code may not be the best thing around...
Check these points:
make sure you assigned your environment to the sandbox (braintree.Environment.Sandbox);
double check (merchantId, publicKey, and privateKey).

Detect when a socket io connection has been changed with ember

Im using ember with socket.io and I want a computed property that changes to if the socket io connection is connected or disconnected.
I am using ember-websockets and here is what I have tried:
socketIOService: service('socket-io'),
socketRoute: 'http://localhost:8080/',
connected: computed('socketIOService',
function()
{
console.log('changed!');
//return (this.get('socketIOService').socketFor(this.get('socketRoute').socket.connected));
}),
startConnection()
{
this.get('connected');
const socket = this.socketIOService.socketFor(this.get('socketRoute'));
socket.on('initialised', this.initialised, this);
},
So this doesnt work because im guessing the service doesnt change. I would like to be able to computer a value from the following...
this.socketIOService.socketFor(this.get('socketRoute'));
But I cant get the sockerFor property in a computed property.
Looking at readme, I think you can use 'open' and 'close' events, w/co computed properties:
startConnection()
{
const socket = this.socketIOService.socketFor(this.get('socketRoute'));
socket.on('open', () => { this.set('connected', true); });
socket.on('close', () => { this.set('connected', false); });
}

Iron-Router randomly returning undefined in Meteor

For some odd reason, iron-router randomly returns undefined.
this.route('pollyShow', {
path: '/polly/:_id',
template: 'polly_show',
notFoundTemplate: 'notFound',
before: function () {
var id = this.params._id;
var poll = Polls.findOne({_id: id});
console.log(poll);
var ip_array = poll.already_voted;
$.getJSON("http://smart-ip.net/geoip-json?callback=?", function(data){
ip_voted = ip_array.indexOf(data.host);
if (ip_voted > -1) {
Router.go('pollyResults', {_id: id});
}
});
},
data: function() {
return Polls.findOne({_id: this.params._id});
}
});
Sometimes it is returning normally while other times it just returns undefined.
Is there any reason behind this?
The problem occurs because the Polly collection is sometimes populated and at other times unpopulated when the route executes.
This problem can be prevented by explicitly waiting on a subscription using waitOn option in the route configuration.
From the docs:
By default, a new Meteor app includes the autopublish and insecure packages, which together mimic the effect of each client having full read/write access to the server's database. These are useful prototyping tools, but typically not appropriate for production applications. When you're ready, just remove the packages.
To remove the packages, call meteor remove <package-name>.
Then you need to explicitly publish records which you want to see on the client on the server:
server/publications.js:
Meteor.publish('all_of_polly', function () { return Polls.find({}); });
And subscribe to it on the client:
this.route('pollyShow', {
path: '/polly/:_id',
template: 'polly_show',
notFoundTemplate: 'notFound',
waitOn: function () { return Meteor.subscribe('all_of_polly'); }
// ...
});

Categories