I took some time to try and solve a problem. I am building a basic Node + Express API. In the app I have created a models folder and will be adding new models as I continue development.
I attempted to write a small autoloader for a directory to automatically load and export my models. This code snippet should work for any modules not just my models folders.
See the following code:
loader.js
const fs = require('fs');
// Autoload modules.
module.exports = fs.readdirSync(__dirname)
// Ignore current file (loader.js)
.filter(f => !__filename.includes(f))
// Require all files in directory
.map(f => require( `./${f}` ))
// Add to final module.exports object using class name
.reduce((prev, curr) => ({...prev, [curr.name]: curr}), {});
My folder structure for the models:
How I import the models into my Routes file:
author.route.js
const { AppResponse, Author } = require('../models/loader');
The question:
Is this a good idea to do something like this? My reasoning is that it would minimize changes when I commit and not require any modifications to my code should I decide to add new functionality to my routes and models folders.
What caveats are there to doing this and would there be a better approach?
Thanks for taking the time to look at this!
