Advertisement
Guest User

Namespaced models

a guest
Aug 23rd, 2016
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var account = new Schema({
  2.     email: String,
  3.     password: String  
  4. });
  5.  
  6. var environment = new Schema({
  7.    dbName: String
  8. });
  9.  
  10. var user = new Schema({
  11.     email: String,
  12.     username: String
  13. });
  14.  
  15.  
  16.  
  17. var moduleExports = {
  18.     account: account,    
  19.     environment: environment,
  20.     user: user
  21. };
  22.  
  23.  
  24. // A list of models which belong to a 'global' database.
  25. var globalModels = ['account'];
  26.  
  27. // A list of models which are 'namespaced'.
  28. var nameSpacedModels = _.map(_.keys( moduleExports ), function(n) {
  29.     if( globalModels.indexOf( n ) === -1 ) {
  30.         return n;
  31.     }
  32. });
  33.  
  34.  
  35. function NamespacedModel(environmentModel) {
  36.     var self = this;
  37.  
  38.  
  39.     self.globalEnvironmentModel = {
  40.         name: config.db.globalDbName,
  41.         dbName: config.db.globalDbName,
  42.     };
  43.  
  44.     if( environmentModel === undefined) {
  45.         self.currentEnvironmentModel = self.globalEnvironmentModel;
  46.     } else {
  47.         self.currentEnvironmentModel = environmentModel;
  48.     }
  49.  
  50.    
  51.  
  52.     self.setDb = function( environmentModel ) {
  53.         if( !environmentModel.dbName ) {            
  54.             return new Error("Failed to set the database, property dbName is not set.");
  55.         } else {
  56.             self.currentEnvironmentModel = environmentModel;
  57.             console.log("Setting db to ", environmentModel.dbName);
  58.         }
  59.  
  60.         var conn = connectionManager.getConnection(environmentModel);
  61.  
  62.         // Bind models to connection
  63.         _.forOwn(nameSpacedModels, function( item ) {
  64.            
  65.             if( item !== undefined ) {
  66.                 self[item] = conn.model(item, moduleExports[item]);
  67.             }
  68.         });
  69.     };
  70.  
  71.  
  72.  
  73.  
  74.  
  75.     // DRY anyone? ;)
  76.     _.forOwn(nameSpacedModels, function( item ) {
  77.  
  78.         var conn = connectionManager.getConnection(self.quizModel);
  79.         if( item !== undefined ) {
  80.             self[item] = conn.model(item, moduleExports[item]);
  81.         }
  82.     });
  83.  
  84.     _.forOwn(globalModels, function( item ) {
  85.         var conn = connectionManager.getConnection(self.defaultQuizModel);
  86.         if( item !== undefined ) {
  87.             self[item] = conn.model(item, moduleExports[item]);
  88.         }
  89.     });
  90. };
  91.  
  92. module.exports = function(ns) {    
  93.     return new NamespacedModel(ns);
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement