Guide on leveraging socket post connection event in socket.io

Apologies for any language barriers. I am facing an issue with my app.js server. I have implemented sockets and utilize the join event within the 'connection' event. A function inside the 'connection' event requires a socket parameter, and I am trying to assign the user to a specific room, whose name is stored in the model of my REST API section of the server (derived from the session). Now, the question arises. How can I assign a user who has connected to the correct room within my REST API model? (this model and its service are triggered when a user requests a page, similar to an authorization check). Additionally, there is another service and model responsible for tasks, handled through a REST API. Within this model, I aim to send messages to all necessary users via sockets when a task is added, excluding the sender. Currently, I am unable to achieve this, as the socket from the connection cannot be passed to the REST API model in any way. App.js

io.on('connection', (socket) => {
  app.set('socket', socket);

  socket.on('disconnect', () => {
    socket.disconnect(true);
  });
});

Controller responsible for sending data to all services and models

const controller = (ServiceClass, params) => {
    return async (req, res, next) => {
        const service = new ServiceClass({
            session: req.session,
            sessionId: req.sessionID,
            cookies: req.cookies,
            socketIo: req.app.get('socketio'),
            socket: req.app.get('socket'),
        });

        const response = await service.run(params(req));
        res.json(response);
    };
}

export default controller;

Here, within the model triggered on every user request to the site, I am attempting to assign the user to the correct room

export default class IsLoggedService extends Service {
    constructor(context) {
        super(context);
    }

    async execute() {
    
    this.context.socket
      .join(`room${userSession.roleId}`);
    }
}

I also inform the client about the created task using the rest api service and model

    this.context.socket
            .to(`room${userSession.roleId}`)
            .emit('test', 'test');

I have thoroughly gone through the socket.io documentation, which suggests using a socket to send a message to everyone except the sender. However, this method is not working as expected, as the message is sent to everyone, including the sender. I have attempted to access the socket within the service and model, but to no avail.

Answer №1

An effective way to implement this is by utilizing the JSON object containing user information received from the socket when a message is sent. By processing this data, the program's logic can be implemented accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The "flickering" effect of the div is like a dance, moving gracefully between fade outs and

I am encountering a similar issue as described in this thread: same problem (fiddle: original fiddle). However, I am still learning JavaScript and struggling to apply the solution provided because my HTML code is slightly different. Can someone please assi ...

Error: The specified module could not be found: Could not resolve 'react-hot-loader/webpack'

After constructing my React project, I encountered the error shown below. How can I resolve this issue? I am utilizing the latest version of react-hot-loader. I have attached a screenshot of the error here ...

Troubleshooting: Issue with Updating Prototype Ajax Function

I am currently utilizing Prototype within the pylons framework and attempting to execute an Ajax call. Below is the structure of my html: <form method="POST" action = "javascript:void(0)" onsubmit = "new Ajax.Updater('graph','/saffron_m ...

Retrieving data from a textbox using JavaScript within an Excel VBA setting

I'm encountering an issue with a Macro in Excel where I need to retrieve the value of an "input type="text"" on a JavaScript webpage. However, the value is not specified in the code (value=""), and it remains unchanged even when the webpage displays t ...

django: no data was submitted in request.POST

I am facing an issue with a REST API endpoint I have created. Here is the code snippet: def post(request, *args, **kwargs): print(request.POST) short_description = request.POST.get("short_description", "") long_description = re ...

Swap the text within the curly braces with the div element containing the specified text

I have an input and a textarea. Using Vue, I am currently setting the textarea's text to match what's in the input field. However, now I want to be able to change the color of specific text by typing something like {#123123}text{/#}. At this poin ...

Failure of jQuery Code Upon Successful Execution

I'm having an issue with my jQuery ajax code. It's functioning perfectly, but I can't seem to get it to change the class of the button that triggers the event when it is successful. The code under success: does not seem to be working as inte ...

Guide on updating and storing changes in a JSON file named 'file.json' using jQuery or JavaScript

I'm working with a JSON file and attempting to make updates using jQuery. However, I'm encountering an issue where I can't seem to save the update once the script has finished running. Is there a way to save the update without relying on se ...

Incorporating DefinitelyTyped files into an Angular 2 project: A step-by-step guide

I am currently developing an application using angular 2 and node.js. My current task involves installing typings for the project. In the past, when starting the server and activating the TypeScript compiler, I would encounter a log with various errors rel ...

JavaScript tool for connecting tags with JSON properties

As a beginner in JS, I am curious if there exists a JS library that can help bind html fields to a JS object. For example: <div class="js_source"> <input field="name" /> <input field="surname" /> <button type="button">S ...

Mastering the Art of Accelerating getJSON Array Data

Currently, I am facing a challenge with retrieving a large array (4MB) of data from the server side. I have been utilizing the jQuery getJSON method to obtain the array data and display it on the browser. However, this process has proven to be quite slow ...

Filtering an array dynamically by utilizing an array of conditions

Can jQuery-QueryBuilder be used to filter an array? This amazing plugin generates a unique array of conditions: condition:"AND" rules: { field:"name" id:"name" input:"select" operator:"equal" type:"string" value:"Albert" } I have ...

Substitute regular expressions with several occurrences by their respective capture groups

I am attempting to use JavaScript to extract only the link text from a string and remove the href tags. The expected behavior is as shown below: <a href='www.google.com'>google</a>, <a href='www.bing.com'>bing</a> ...

Utilizing jQuery to manipulate dynamic elements on the DOM

Struggling to dynamically generate HTML using jQuery and facing challenges with adding a nested loop to generate specific target HTML code. The target HTML code is as follows: <div class="daily-featured__video-social"> <ul class="share-tools_ ...

web address ajax search

Not sure what I'm searching for, so if you could help me identify what this is and suggest keywords to look up. http://website.com/page.php#article23 The number sign isn't a typical URL request method like GET or POST; it's more like an "A ...

Using JavaScript to create CSS animations triggered on hover

Looking for a CSS Animation that will play forward once when the mouse enters a specific div, and then play in reverse when the mouse leaves. Check out my JsFiddle here. The div with the class ".item" should trigger the mouse enter event. The animation co ...

Issue with jQuery 'on' event not triggering following 'load' event

I am facing an issue on a page where similar events occur but when new content is loaded halfway through, most of the jQuery functionalities stop working. The scenario involves answering questions in a 'game' format using AJAX calls. Once all que ...

Creating a SAS URL for Azure Blob storage in Node.js using the generateBlobSASQueryParameters method from the @azure/storage-blob module

Hello, I am working with an Azure storage account where I upload and create a SAS URL to download images. Below is the code snippet that I have used: const { BlobServiceClient, StorageSharedKeyCredential, BlobSASPermissions, generateBlobSASQueryPar ...

converting nested object structures in typescript

I'm trying to flatten a nested object in my Loopback and Typescript controller Here's the structure of my model : export class SampleModel { id: number; code: number; guide?: string; gradeData?: string; } Take a look at this example obj ...

Retrieving a variable within a try-catch statement

I am trying to implement a function: function collect_user_balance() { userBalance = 0; try { var args = { param: 'name'; }; mymodule_get_service({ data: JSON.stringify(args), s ...