updated webpack to build to index.js and moved sql to take a config

This commit is contained in:
bill bittner 2018-03-08 13:18:34 -08:00
parent 7f1fbae366
commit 6d8884ca14
8 changed files with 110 additions and 126 deletions

2
.gitignore vendored
View file

@ -3,5 +3,3 @@ node_modules
config/sequelizeCliConfig.js config/sequelizeCliConfig.js
config/speechConfig.js config/speechConfig.js
public/bundle public/bundle
server.js
webpack.config.js

View file

@ -5,11 +5,6 @@ module.exports = {
analytics: { analytics: {
googleId: null, // google id for analytics tracking; leave `null` if not applicable googleId: null, // google id for analytics tracking; leave `null` if not applicable
}, },
sql: {
database: null, // name of mysql database
username: null, // username for mysql
password: null, // password for mysql
},
logging: { logging: {
logLevel : null, // options: silly, debug, verbose, info logLevel : null, // options: silly, debug, verbose, info
slackWebHook : null, // enter a webhook if you wish to push logs to slack; otherwise leave as `null` slackWebHook : null, // enter a webhook if you wish to push logs to slack; otherwise leave as `null`

View file

@ -2,28 +2,6 @@ const logger = require('winston');
const db = require('../models'); const db = require('../models');
module.exports = { module.exports = {
getTrendingClaims (startDate) {
logger.debug('retrieving trending');
return new Promise((resolve, reject) => {
// get the raw requests data
db.getTrendingFiles(startDate)
.then(fileArray => {
let claimsPromiseArray = [];
if (fileArray) {
fileArray.forEach(file => {
claimsPromiseArray.push(db.Claim.resolveClaim(file.name, file.claimId));
});
return Promise.all(claimsPromiseArray);
}
})
.then(claimsArray => {
resolve(claimsArray);
})
.catch(error => {
reject(error);
});
});
},
getRecentClaims () { getRecentClaims () {
logger.debug('retrieving most recent claims'); logger.debug('retrieving most recent claims');
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {

View file

@ -1,82 +1,78 @@
// const fs = require('fs');
// const path = require('path');
const Sequelize = require('sequelize'); const Sequelize = require('sequelize');
// const basename = path.basename(module.filename);
const logger = require('winston'); const logger = require('winston');
const config = require('../config/speechConfig.js');
const { database, username, password } = config.sql;
const db = {};
// set sequelize options module.exports = (mysqlConfig) => {
const sequelize = new Sequelize(database, username, password, { const { database, username, password } = mysqlConfig;
host : 'localhost', const db = {};
dialect : 'mysql', // set sequelize options
dialectOptions: {decimalNumbers: true}, // fix to ensure DECIMAL will not be stored as a string const sequelize = new Sequelize(database, username, password, {
logging : false, host : 'localhost',
pool : { dialect : 'mysql',
max : 5, dialectOptions: {decimalNumbers: true}, // fix to ensure DECIMAL will not be stored as a string
min : 0, logging : false,
idle : 10000, pool : {
acquire: 10000, max : 5,
}, min : 0,
}); idle : 10000,
acquire: 10000,
sequelize },
.authenticate()
.then(() => {
logger.info('Sequelize has established mysql connection successfully.');
})
.catch(err => {
logger.error('Sequelize was unable to connect to the database:', err);
}); });
// manually add each model to the db // establish mysql connection
const Certificate = require('./certificate.js'); sequelize
const Channel = require('./channel.js'); .authenticate()
const Claim = require('./claim.js'); .then(() => {
const File = require('./file.js'); logger.info('Sequelize has established mysql connection successfully.');
const Request = require('./request.js');
const User = require('./user.js');
db['Certificate'] = sequelize.import('Certificate', Certificate);
db['Channel'] = sequelize.import('Channel', Channel);
db['Claim'] = sequelize.import('Claim', Claim);
db['File'] = sequelize.import('File', File);
db['Request'] = sequelize.import('Request', Request);
db['User'] = sequelize.import('User', User);
// run model.association for each model in the db object that has an association
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
logger.info('Associating model:', modelName);
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
// add an 'upsert' method to the db object
db.upsert = (Model, values, condition, tableName) => {
return Model
.findOne({ where: condition })
.then(obj => {
if (obj) { // update
logger.debug(`updating record in db.${tableName}`);
return obj.update(values);
} else { // insert
logger.debug(`creating record in db.${tableName}`);
return Model.create(values);
}
}) })
.catch(function (error) { .catch(err => {
logger.error(`${tableName}.upsert error`, error); logger.error('Sequelize was unable to connect to the database:', err);
throw error;
}); });
};
// add a 'getTrendingFiles' method to the db object. note: change this to get claims directly. might need new association between Request and Claim // manually add each model to the db object
db.getTrendingFiles = (startDate) => { const Certificate = require('./certificate.js');
return db.sequelize.query(`SELECT COUNT(*), File.* FROM Request LEFT JOIN File ON Request.FileId = File.id WHERE FileId IS NOT NULL AND nsfw != 1 AND trendingEligible = 1 AND Request.createdAt > "${startDate}" GROUP BY FileId ORDER BY COUNT(*) DESC LIMIT 25;`, { type: db.sequelize.QueryTypes.SELECT }); const Channel = require('./channel.js');
}; const Claim = require('./claim.js');
const File = require('./file.js');
const Request = require('./request.js');
const User = require('./user.js');
db['Certificate'] = sequelize.import('Certificate', Certificate);
db['Channel'] = sequelize.import('Channel', Channel);
db['Claim'] = sequelize.import('Claim', Claim);
db['File'] = sequelize.import('File', File);
db['Request'] = sequelize.import('Request', Request);
db['User'] = sequelize.import('User', User);
module.exports = db; // run model.association for each model in the db object that has an association
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
logger.info('Associating model:', modelName);
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
// add an 'upsert' method to the db object
db.upsert = (Model, values, condition, tableName) => {
return Model
.findOne({
where: condition,
})
.then(obj => {
if (obj) { // update
logger.debug(`updating record in db.${tableName}`);
return obj.update(values);
} else { // insert
logger.debug(`creating record in db.${tableName}`);
return Model.create(values);
}
})
.catch(function (error) {
logger.error(`${tableName}.upsert error`, error);
throw error;
});
};
return db;
};

View file

@ -6,8 +6,8 @@
"scripts": { "scripts": {
"test": "mocha --recursive", "test": "mocha --recursive",
"test-all": "mocha --recursive", "test-all": "mocha --recursive",
"start": "node server.js", "start": "node index.js",
"start-dev": "nodemon server.js", "start-dev": "nodemon index.js",
"lint": "eslint .", "lint": "eslint .",
"fix": "eslint . --fix", "fix": "eslint . --fix",
"precommit": "eslint .", "precommit": "eslint .",

View file

@ -9,7 +9,6 @@ const logger = require('winston');
const helmet = require('helmet'); const helmet = require('helmet');
const PORT = 3000; // set port const PORT = 3000; // set port
const app = express(); // create an Express application const app = express(); // create an Express application
const db = require('./models'); // require our models for syncing
const passport = require('passport'); const passport = require('passport');
const cookieSession = require('cookie-session'); const cookieSession = require('cookie-session');
@ -62,23 +61,34 @@ app.set('view engine', 'handlebars');
app.use(populateLocalsDotUser); app.use(populateLocalsDotUser);
// start the server // start the server
db.sequelize const startServer = (mysqlConfig) => {
.sync() // sync sequelize const db = require('./models')(mysqlConfig); // require our models for syncing
.then(() => { // require routes db.sequelize
require('./routes/auth-routes.js')(app); // sync sequelize
require('./routes/api-routes.js')(app); .sync()
require('./routes/page-routes.js')(app); // require routes
require('./routes/serve-routes.js')(app); .then(() => {
require('./routes/fallback-routes.js')(app); require('./routes/auth-routes.js')(app);
const http = require('http'); require('./routes/api-routes.js')(app);
return http.Server(app); require('./routes/page-routes.js')(app);
}) require('./routes/serve-routes.js')(app);
.then(server => { // start the server require('./routes/fallback-routes.js')(app);
server.listen(PORT, () => { const http = require('http');
logger.info('Trusting proxy?', app.get('trust proxy')); return http.Server(app);
logger.info(`Server is listening on PORT ${PORT}`); })
// start the server
.then(server => {
server.listen(PORT, () => {
logger.info('Trusting proxy?', app.get('trust proxy'));
logger.info(`Server is listening on PORT ${PORT}`);
});
})
.catch((error) => {
logger.error(`Startup Error:`, error);
}); });
}) };
.catch((error) => {
logger.error(`Startup Error >> ${error.message}`, error); module.exports = (config) => {
}); const { mysqlConfig } = config;
startServer(mysqlConfig);
};

7
webpack.config.js Normal file
View file

@ -0,0 +1,7 @@
const serverBaseConfig = require('./webpack.server.common.js');
const clientBaseConfig = require('./webpack.client.common.js');
module.exports = [
serverBaseConfig,
clientBaseConfig,
];

View file

@ -8,11 +8,11 @@ module.exports = {
__dirname: false, __dirname: false,
}, },
externals: [nodeExternals()], externals: [nodeExternals()],
entry : ['babel-polyfill', 'whatwg-fetch', './index.js'], entry : ['babel-polyfill', 'whatwg-fetch', './server.js'],
output : { output : {
path : Path.join(__dirname, '/'), path : Path.join(__dirname, '/'),
publicPath: '/', publicPath: '/',
filename : 'server.js', filename : 'index.js',
}, },
module: { module: {
rules: [ rules: [