@iobroker/js-controller-common-db
Version:
The Library contains the common utils for the ioBroker controller which can be used by db classes too, as they do not rely on the db (circular dependencies).
74 lines • 2.35 kB
JavaScript
/**
* Function to create an AdapterStore constructor
*
* @param session The session object, like "express-session"
* @param defaultTtl the default time to live in seconds
* @returns the constructor to create a new AdapterStore
*/
export function createAdapterStore(session, defaultTtl = 3600) {
const Store = session.Store;
class AdapterStore extends Store {
adapter;
constructor(options) {
super(options);
this.adapter = options.adapter;
options = options || {};
if (!options.cookie) {
options.cookie = { maxAge: defaultTtl };
}
Store.call(this, options);
}
/**
* Attempt to fetch session by the given `sid`.
*
* @param sid Session ID
* @param fn callback
*/
get(sid, fn) {
this.adapter.getSession(sid, (obj) => {
if (obj) {
if (fn) {
return fn(null, obj);
}
}
else if (fn) {
return fn();
}
});
}
/**
* Commit the given `sess` object associated with the given `sid`.
*
* @param sid Session ID
* @param ttl Time to live
* @param sess the session
* @param fn callback
*/
set(sid, ttl, sess, fn) {
if (typeof sess === 'function') {
fn = sess;
sess = ttl;
// analyse if the session is stored directly from express session
ttl = sess?.cookie?.originalMaxAge
? Math.round(sess.cookie.originalMaxAge / 1000)
: defaultTtl;
}
ttl = ttl || defaultTtl;
this.adapter.setSession(sid, ttl, sess, function (err) {
// @ts-expect-error fix later
fn?.call(this, err);
}); // do not use here => !!!
}
/**
* Destroy the session associated with the given `sid`.
*
* @param sid Session ID
* @param fn callback
*/
destroy(sid, fn) {
this.adapter.destroySession(sid, fn);
}
}
return AdapterStore;
}
//# sourceMappingURL=session.js.map