I wrote a utility for generating and saving sessions in a MongoDB database as well as checking the session to make sure it's valid.
I'm a beginner when it comes to promises and I have a feeling that either I'm using them improperly or I'm not taking full advantage of them.
Here's the session utility:
// Dependencies
var crypto = require('crypto'),
config = require('../../config'),
Session = require('../database/schemas/session');
// Generate Function
var generate = function(length) {
// Return a promise
return new Promise(function(resolve, reject) {
// Create a random value
crypto.randomBytes(length, function(error, buffer) {
// Determine if an error occurred
if (error) {
// Reject with error
reject(error);
} else {
// Resolve with session ID
resolve(buffer.toString('hex'));
}
});
});
}
// Create Function
exports.create = function(account_id) {
// Return a promise
return new Promise(function(resolve, reject) {
// Generate the session ID and fetch the promise
generate(config.session.length)
.then(function(sid) {
// Save the session in the database and return the promise
return(new Session({_id: sid, account_id: account_id}).save());
})
.then(function(session) {
// Determine if session is not defined
if (!session) {
// Reject
reject();
} else {
// Resolve with the session ID
resolve(session._id);
}
})
.catch(reject);
});
}
// Check Function
exports.check = function(sid) {
// Return a promise
return new Promise(function(resolve, reject) {
// Query for a session with the provided ID and fetch the promise
Session.findOne({_id: sid}).lean().exec()
.then(function(session) {
// Determine if no session was found or if it expired
if (!session) {
// Resolve with false
resolve(false);
} else if (session.expires < Date.now()) {
// Resolve with false
resolve(false);
} else {
// Resolve with true by default
resolve(true);
}
})
.catch(reject);
});
}
Here's the session schema:
// Dependencies
var mongoose = require('mongoose'),
config = require('../../../config');
// Session Schema
var sessionSchema = mongoose.Schema({
_id: {type: String},
account_id: {type: mongoose.Schema.Types.ObjectId, required: true},
expires: {type: Date, required: true, default: Date.now() + config.session.expires}
});
// Export the model of the schema
module.exports = mongoose.model('session', sessionSchema);
checkmethod is not very readable too. How about thisif (!session || session.expires < Date.now()) { resolve(false); } ...? \$\endgroup\$ifstatements as well. Thanks for the feedback. \$\endgroup\$