Created
November 19, 2014 12:30
-
-
Save alexbeletsky/c6a6ec365aebc180ce22 to your computer and use it in GitHub Desktop.
Simple Multi-tenancy for MongoDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var tenancy = require('../utils/tenancy'); | |
function shiftsModel(mongo) { | |
function create(user, shift, callback) { | |
mongo.shifts.save(tenancy(user, shift), tenancy(callback)); | |
} | |
function getByWeek(user, week, callback) { | |
mongo.shifts.find(tenancy(user, {week: +week}), tenancy(callback)); | |
} | |
function getByWeekByDay(user, week, day, callback) { | |
mongo.shifts.findOne(tenancy(user, {week: +week, day: +day}), tenancy(callback)); | |
} | |
return { | |
create: create, | |
getByWeek: getByWeek, | |
getByWeekByDay: getByWeekByDay | |
}; | |
} | |
module.exports = shiftsModel; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var util = require('util'); | |
var _ = require('underscore'); | |
function removeTenant(result) { | |
return _.omit(result, 'user'); | |
} | |
function wrapCallback(callback) { | |
return function (err, results) { | |
if (err) { | |
return callback(err); | |
} | |
return util.isArray(results) ? callback(null, results.map(removeTenant)) : callback(null, removeTenant(results)); | |
}; | |
} | |
function tenancy(user, data) { | |
if (typeof user === 'function') { | |
return wrapCallback(user); | |
} | |
return _.extend(data, {user: _.pick(user, ['id', 'firstname', 'lastname', 'email'])}); | |
} | |
module.exports = tenancy; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment