Saving state between RPC calls

92 views
Skip to first unread message

Benjamin Polidore

unread,
Jul 6, 2012, 10:05:00 PM7/6/12
to socket...@googlegroups.com
hey, this might be a dumb Q, but if you want to save state between RPC method calls, do you have to do anything special? variables i declare outside the return scope are available in the closure, but i can't set them. does socketstream reinstantiate the return object each call to rpc or am i making a silly javascript faux pas?  

Here's an example-- this logs Object when it should log Timer:


Just to prove I'm not going crazy: this is valid JS.

var a = {}
undefined
var c = { on: function() { a = 9 }, off: function() {console.log(a); a = 10}}
undefined
c.on()
undefined
a
9
c.off()
9
undefined
a
10

Benjamin Polidore

unread,
Jul 8, 2012, 9:13:27 AM7/8/12
to socket...@googlegroups.com
ok, took a look at the source, and it looks like the RPC responders get constructed and discarded each call.  I know I could put state in a db, but I'm just trying to write an example app, and if I were to, for example, cache a value in a real application, I can't do it in RPC.  Any thoughts?

Owen B

unread,
Jul 8, 2012, 9:50:07 AM7/8/12
to socket...@googlegroups.com
Hey Benjamin

Yes you're right, we need to run the exports.action closure each time to allow the middleware to execute.

Therefore if you really don't want to use a db, just put your variable outside of the closure:

  var intervalId = {};

exports.actions = function(req,res,ss) {
  var crypto = require('crypto');

  return {
    on: function() {
      etc etc...

Owen

Benjamin Polidore

unread,
Jul 8, 2012, 9:59:17 AM7/8/12
to socket...@googlegroups.com
Thanks. That makes sense. 

Benjamin Polidore

unread,
Jul 9, 2012, 11:38:48 AM7/9/12
to socket...@googlegroups.com
So really anything expensive (such as nodejs require()) should probably be done outside the closure if possible for performance reasons, right?

Owen B

unread,
Jul 9, 2012, 11:49:57 AM7/9/12
to socket...@googlegroups.com
In general yes, though require() is a synchronous operation which is cached by Node, so it will only ever load the file once.

The req.use() commands can't live outside the closure as they must be evaluated upon each request.

Owen
Reply all
Reply to author
Forward
0 new messages