npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongosess

v0.4.0

Published

Session storage, utilizing MongoDB.

Downloads

13

Readme

MongoSess

MongoSess is a Node.js module for handling session data, utilizing MongoDB for storage. Its main point of interest is that it can be used without frameworks; if you're looking for something to use with Express/Connect, there are better alternatives.

Installation

$ npm install mongosess

API

Note: All callbacks, except the one passed to MongoSess.connect( ), are the standard callback(err, result) style.

Callbacks for the instance methods (set, get, etc.) are all optional; if none is given, they return a promise.

MongoSess.connect( options, callback )

MongoSess.connect( ) establishes the connection. Takes an options object and a parameter-less callback to be called once the connection has been established. The options object has the form:

{
  // Name of database:
  db: 'example',

  // Name of collection. Optional; defaults to 'sessions'
  collection: 'sessionCollection',

  // One or more servers to connect to, and their options:
  servers: [{
    host: 'localhost',
    port: 10034,            // Optional, defaults to 27017
    opts: {                 // Optional as well.
      autoReconnect : false,
      poolSize : 200
    }
  }, {
    host: 'hostX',
    post: portX
  }],

  // Authentication credentials, if necessary:
  auth: {
    user: 'foo',
    pass: 'bar'
  },

  // Time in ms the data lives in the database. Defaults to two weeks.
  expires: 1000 * 60 * 60 * 24 * 7
}

MongoSess.close( ) OR MongoSess.disconnect( )

Closes the previously opened database connection.

session = new MongoSess( request, response [, options ] )

Create a new session store for the current request and response. The new constructor is optional. You may pass in options relating to cookies; specifically, cookie name, keys for signing using Keygrip, and time in ms before the cookie expires. Setting expires to 0 causes the session cookie to be deleted when the browser is closed. See the example for more detail.

session.set( { key1: val1 [, key2: val2, ..., keyN, valN ] }, callback )

This sets the key(s) equal to value(s) for the session.

Note: trying to overwrite the _id field raises an error. You probably also want to leave the createdAt field alone, but MongoSess won't complain if you tamper with it.

session.get( [ key, ] callback )

Retrieves the value associated with the given key from the session data. If no key is given, gets the entire session.

session.del( key1, [ key2, ..., keyN, ] callback )

Deletes the provided keys and their values from the session data.

Note: As with set( ), trying to delete the _id field raises an error. It's probably also a good idea to leave the createdAt field alone, otherwise the session may persist in the database forever. That's probably not what you want to do.

session.end( callback )

Deletes the session from the database and deletes the user's cookies.

session.expire( )

Makes the tracking cookie session-only - that is, it gets deleted when the user closes their browser - when it had been previously set to expire at a later date. Note that this does not change the expiry date of the session in the database, as the user may choose to leave their browser open for lengthy periods of time.

Example

var MongoSess = require('mongosess'),
    KeyGrip = require('keygrip'),
    http = require('http')

// Connect to MongoDb on port 12345 of localhost, using the 'example' database.
MongoSess.connect({
  db: 'example',
  servers: [{
    host: 'localhost',
    port: 12345
  }]
}, function () {

  // Create an http server listening on port 3000.
  var server = http.createServer(function (req, res) {

    // You can decorate like so:
    req.session = res.session = MongoSess(req, res, {
      cookieName: 'sessionCookie',  // Cookie name will be 'sessionCookie'
      keys: ['secret1', 'secret2'], // Keys to sign cookie with.
      expires: 0                    // Cookie will be deleted when the browser is closed.
    });

    // Set some data.
    res.session.set({ name: 'john doe'}, function (err, result) {
      res.writeHead(200)
      res.end('Your name is John Doe.')
    })

    /*
     * Some time later...
     */

    // Get some data, promise style.
    req.session.get('name')
      .then(function (name) {
        res.writeHead(200)
        res.end('Hello, ' + name + '.')
      })

    /*
     * Even later...
     */

    // Delete data.
    res.session.del('name', function (err, deleted) {
      res.writeHead(200)
      res.end('You no longer have a name.')
    })

    /*
     * And eventually...
     */

    // End the session.
    res.session.end(function (err, ended) {
      res.writeHead(200)
      res.end('Goodbye!')
    })
  })

  server.listen(3000)

  // Maybe close the connection when the server closes.
  server.on('close', MongoSess.close)
  // Alternatively: MongoSess.disconnect()
})

Thanks

Inspired by isaacs/redsess and diversario/connect-mongostore.

License

MIT. See LICENSE