Created
February 26, 2016 17:42
-
-
Save jhyland87/b84acc8c1ebae26c8d7c to your computer and use it in GitHub Desktop.
Loading Mongoose model files
This file contains hidden or 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
'use strict' | |
import path from 'path' | |
import fs from 'fs' | |
import _ from 'moar-lodash' | |
import * as appRoot from 'app-root-path' | |
const log = appRoot.require('./dist/lib/utils/logger')({ model: 'Index (loader)' }) | |
module.exports = ( Mongoose ) => { | |
const ignoreFiles = ['index.js'] | |
log.debug(`Model index loaded, preparing to load models (except the files ${ignoreFiles.join(', ')})`) | |
if( ! Mongoose ) | |
throw new Error('Need to pass a Mongoose object to the model index to load all models') | |
// Get all the files found in the current directory | |
const files = fs.readdirSync( __dirname ) | |
log.debug(`Files found: ${files.join(', ')}`) | |
// This object will be populated and returned | |
const models = {} | |
// Loop through the files in this directory, loading them as Mongoose | |
// models, and adding them to the models object to be returned | |
_.forEach( files, f => { | |
// Get the full path of the file | |
let file = path.resolve( __dirname, f ) | |
log.debug( `Processing path ${file}...` ) | |
// Skip any folders (EG: ./middleware folder) | |
if( ! fs.lstatSync( file ).isFile() ){ | |
log.info( `Ignoring the path ${file} - It's not a file` ) | |
return | |
} | |
// Skip this if its listed as a file to ignore | |
if( _.indexOf( ignoreFiles, f ) !== -1 ){ | |
log.info( `Ignoring the file ${file} - found in ignore list` ) | |
return | |
} | |
// Get the model name from the file name | |
const modelName = f.match( /(.*)\.js/ )[ 1 ] | |
// Convert it to ucfirst | |
const model = _.chain( modelName ).toLower().upperFirst().value() | |
//log.debug(`Loading file ${f} as Mongoose model ${model}`) | |
// An atempt to circumvent the OverwriteModelError error | |
if( _.isUndefined( models[ model ] ) ) { | |
// Load it as a model by passing the mongoose object | |
models[ model ] = require( `./${modelName}` )( Mongoose ) | |
log.debug(`Mongoose model ${model} successfully loaded by model index`) | |
} | |
} ) | |
log.debug(`Models being returned: ${_.keys( models ).join(', ')}`) | |
return models | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment