Question

I am new to Node.js and server-side JS in general.

I am coming from Java EE and I am used to use stateful objects (not EJB, I am using CDI), for instance, for MVC. My aim is to keep some data that is tied to e.g. a session.

CDI in Java EE knows the following state scopes:

  • Application scoped (= same as the singleton pattern)
  • Session scoped (state is kept for a user's session lifecycle, e.g. the logged in user)
  • Conversation scoped (state is kept for an identified conversation, e.g. a shopping cart)
  • Flash scoped (state is kept between two requests)

How to do all that stuff with Node without using a database, just using stateful objects?

Était-ce utile?

La solution

You'll need something like connect to track session state for you as that is the least-trivial of these scopes. Once you have that you can do things as follows.

  • Application scoped (= same as the singleton pattern)
    • set a property on your HTTP server instance: myServer.totalRequestsServed = 0
    • or you can use a process-wide global: global.totalRequestsServed = 0
  • Session scoped (state is kept for a user's session lifecycle, e.g. the logged in user)
    • use the connect session middleware for this: req.session.user = myUser
  • Conversation scoped (state is kept for an identified conversation, e.g. a shopping cart)
    • I'm not totally clear on what you mean by "conversation scope" but I would stick this on the session user or in a shared hash object. session.user.shoppingCart = {}
  • Flash scoped (state is kept between two requests)
    • Use either the session or the request for this. There are existing modules in npm to give you helpers like req.flash("Welcome!"). See connect-flash for example.

Autres conseils

Just like in the Java world, to be scalable, you'd need either server affinity or an external store for session data. Storing session scoped data on the server (as well as replicating it across all clones) is not scalable.

  • Server affinity can be arranged at infra level via a cookie. No change needed in the application.
  • External store support in NodeJS is available via the express-session middleware. It supports a number of session stores out of the box.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top