skip to Main Content

A controller loses its state across requests. But can we use services to keep objects across requests?

My use case is this: I have to maintain a pool of twitter streams(via some library like npm twitter)
On hitting a controller, a user initiates a stream. I would like to maintain a pool of all streams somewhere. Services directory looks like the proper place to put those streams(in an array).

Then on hitting another controller, i would like to fetch the appropriate stream from that array and destroy that so that it stops the streaming api.

So is service folder good for it? or do I need to use some caching library as here?

EDIT:

The twitter stream represent active and persistent connection to twitter apis. So I don’t think they can be stored in db(or cached into secondary memory).

2

Answers


  1. I think you can use any require able module this way, sort of treating it like an instance of an OOP class with public getters and setters in module.exports.

    Say you have a service called myService.js:

    var pool = []; // this will be initialized when the app starts
    
    module.exports = {
        addToPool: function(obj) {
            pool.push(obj);
        },
    
        getPool: function() {
            return pool;
        } 
    };
    

    Then any controller (etc) could access the pool:

    var myserv = require('myService');
    myserv.addToPool({'one': 'two'});
    var pool = myserv.getPool();
    

    HOWEVER,

    I have never used active memory to store things this way. How big is your pool going to get? Are you sure you don’t want to do this through a database?

    One other caution, I’m not positive there won’t be some interference, ex pool being iterated over by one method initiated by one user, and being altered by another method initiated by another user, etc.

    Login or Signup to reply.
  2. Yes it can, and Services is the right place for it, because Services in SailS is a place for logic that you need to use in many places. But I need to advise you to not do it this way! Instead, a more stateless approach can be made: Data is stored only in the database, then states can be derived from data from the DB + input from your user. This way you can scale you server without any problems:

    Let’s say that I have one instance of my Sails app on server A. Then I launch server B to keep up the demand. Server A WILL NOT share variables with server B, but they can share a database! And a SQL DB can provide some security for concurrency and other problems, but REDIS should be enough.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search