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
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 inmodule.exports
.Say you have a service called
myService.js
:Then any controller (etc) could access the pool:
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.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 launchserver B
to keep up the demand.Server A
WILL NOT share variables withserver 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.