connect-once
Memorizing async function result
This module solves problem with connection creating in Node.JS.
Most known example - MongoDB connections. Often you want to get one connection shared with all incoming requests. However there are two edges, that can hurt you, when your application starting under significant load. Connection should be:
- Created once for all requests, that are coming at the same time - otherwise you can take down your database connection pool.
- Ready before first request arrives - to reduce page loading time.
Also it is nice to have some retries, when database decides to take a rest. For this (and other) tasks connect-once was written.
Usage
You can see express-mongo-db and express-mongoose-db as real-life examples of connect-once usage.
Install package with npm:
npm i connect-once --save
Then create a connection:
var connectOnce = ; var connection = retries: 60 reconnectWait: 1000 MongoClientconnect 'mongodb://localhost/test'; connection;
Heartbeat
Heartbeat is useful, when you want check connection from time to time. For example, if you working with mongodb and cache connection to db - what happens when server, which connection binded to goes to heaven? Connection is lost and programmer should recreate it.
Note: for now there is no way to stop heartbeats.
var connectOnce = ; var connection = { db; } MongoClientconnect 'mongodb://localhost/test'; connection;
Force retry (update cached value)
There are interesting use case of connect-once in a wild: it can be used as some sort of in-memory cache. Because it consumes general function with callback - there is no difference, what to memorize - connection or abstract object.
Suppose you have a function getCache(callback)
, that invokes callback
with next arguments: null, new Date()
. To update cached value from time-to time you can use next code:
var connectOnce = ;var connection = getCache;;
Also available
event will be fired every 5000 seconds.
API
You can read source code (65 sloc!) or generated documentation of Connection class which is not very nice.
License
(MIT License) (c) 2013 Vsevolod Strukchinsky (floatdrop@gmail.com)