javascript - Store object dynamically in object -


this question might sound stupid or little simple got stuck.

i have node.js app , need store clients able send information specific client specific other client.

var clients = { };  var chat     = io.of('/chat') .on('connection', function(socket) {     socket     .on('ehlo', function(data) {         // mysql queries here etc client's data,         // example session_id, customer name, ...          // got stuck here, need save socket in customers object like:         clients.(customer + data.get_customer_id) = { socket: socket }; 

i later need able access property different scope etc.

basically lack idea of how these abstract methods can implemented:

clients.addclient({ id: 123, socket: socket}); 

and later find them by:

x = clients.findbyid(123); // x should { id: 123, socket: socket} 

well, can define clients module first.

//clients.js "use strict";  var clients = {     _db: [] };  clients.findbyid = function(id){     for(var i=0; < this._db.length; i++){         var client = this._db[i];         if(client.id === id){             return client;         }     }     return null; };  clients.addclient = function(client) {     if(!this.findbyid(client.id)){         this._db.push(client);     } };  module.exports = clients; 

the way node.js works cache module after it's initialized. after use first time. means every time require it, same clients object. can in hypothetical module1.js:

//module1.js var clients = require('./clients'); clients.addclient(newclient); 

and later in module can gain access same data structure:

//module2.js var clients = require('./clients'); var client = clients.findbyid(id); 

and that's it, can gain access same data structure different contexts. point here modules share same clients object.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -