Skip to content

Instantly share code, notes, and snippets.

@snewell92
Created May 25, 2017 19:08
Show Gist options
  • Save snewell92/a7d2719a1519d2d2e6f6101f1b87e7a1 to your computer and use it in GitHub Desktop.
Save snewell92/a7d2719a1519d2d2e6f6101f1b87e7a1 to your computer and use it in GitHub Desktop.
Asynchrnous loading in feathers
/************************************************/
/* This file's full path would be .src/mysql.js */
/************************************************/
var Promise = require('bluebird');
const Sequelize = require('sequelize');
const fs = Promise.promisifyAll(require('fs'));
const _ = require('lodash');
module.exports = async function(app) {
const connectionString = app.get('mysql');
const sequelize = new Sequelize(connectionString, {
dialect: 'mysql',
logging: false
});
app.set('sequelizeClient', sequelize);
// asynchronously iterate over all the files in models and and invoke each model function to create
// the models. sequelize is the instance, Sequelize holds static DataTypes that the models need
await fs.readdirAsync("./src/models")
.map(fileName => {
let model = require('./models/' + fileName);
model(sequelize, Sequelize);
});
/* After all models are registered we can associate them together */
_.map(Object.keys(sequelize.models), n => sequelize.models[n])
.filter(m => m.associate !== undefined)
.forEach(m => m.associate());
// sync up to the database
sequelize.sync();
return await app;
};
/*********************************************************/
/* This file's full path would be .src/services/index.js */
/*********************************************************/
var Promise = require('bluebird');
const _ = require('lodash');
const path = require('path');
const fs = Promise.promisifyAll(require('fs'));
module.exports = async function (app) {
let configureService = async service => {
// we can't use app.configure(service)
// since that will break parallelism
return await (service.bind(app))();
}
let getDirectories = dirPath => {
return fs.readdirAsync(dirPath)
.filter(file =>
fs.lstatSync(path.join(dirPath, file)).isDirectory()
);
}
let getService = dirName =>
require(`./${dirName}/${dirName}.service.js`);
// We can parallelize service configuration
// If we ever get services that depend on one another, we
// can set that up too, but this code will need to change
try {
let promises = getDirectories('./src/services')
.map(getService)
.map(configureService); // start parallel work
await Promise.all(promises); // wait for work to finish
} catch (err) {
console.error("\n\nError configuring services!\n");
console.error("********************");
console.error(err);
console.error("********************\n\n");
app.configure(schools);
}
return app;
app.configure(schools);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment