@foal/mongodb
Version:
MongoDB package for FoalTS session
82 lines (81 loc) • 2.43 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MongoDBStore = void 0;
const core_1 = require("@foal/core");
const mongodb_1 = require("mongodb");
/**
* MongoDB store.
*
* @export
* @class MongoDBStore
* @extends {SessionStore}
*/
class MongoDBStore extends core_1.SessionStore {
mongoDBClient;
collection;
setMongoDBClient(mongoDBClient) {
this.mongoDBClient = mongoDBClient;
}
async boot() {
if (!this.mongoDBClient) {
const mongoDBURI = core_1.Config.getOrThrow('settings.mongodb.uri', 'string', 'You must provide the URI of your database when using MongoDBStore.');
this.mongoDBClient = await mongodb_1.MongoClient.connect(mongoDBURI);
}
this.collection = this.mongoDBClient.db().collection('sessions');
this.collection.createIndex({ sessionID: 1 }, { unique: true });
}
async save(state, maxInactivity) {
try {
await this.collection.insertOne({
sessionID: state.id,
state,
});
}
catch (error) {
if (error.code === 11000) {
throw new core_1.SessionAlreadyExists();
}
// TODO: test this line.
throw error;
}
}
async read(id) {
const session = await this.collection.findOne({ sessionID: id });
if (session === null) {
return session;
}
return session.state;
}
async update(state, maxInactivity) {
await this.collection.updateOne({
sessionID: state.id
}, {
$set: { state }
}, {
upsert: true,
});
}
async destroy(id) {
await this.collection.deleteOne({ sessionID: id });
}
async clear() {
await this.collection.deleteMany({});
}
async cleanUpExpiredSessions(maxInactivity, maxLifeTime) {
await this.collection.deleteMany({
$or: [
{ 'state.createdAt': { $lt: Math.trunc(Date.now() / 1000) - maxLifeTime } },
{ 'state.updatedAt': { $lt: Math.trunc(Date.now() / 1000) - maxInactivity } }
]
});
}
/**
* Closes the connection to the database.
*
* @memberof MongoDBStore
*/
async close() {
await this.mongoDBClient.close();
}
}
exports.MongoDBStore = MongoDBStore;