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/speechConfig.js
public/bundle
server.js
webpack.config.js

View file

@ -5,11 +5,6 @@ module.exports = {
analytics: {
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: {
logLevel : null, // options: silly, debug, verbose, info
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');
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 () {
logger.debug('retrieving most recent claims');
return new Promise((resolve, reject) => {

View file

@ -1,82 +1,78 @@
// const fs = require('fs');
// const path = require('path');
const Sequelize = require('sequelize');
// const basename = path.basename(module.filename);
const logger = require('winston');
const config = require('../config/speechConfig.js');
const { database, username, password } = config.sql;
const db = {};
// set sequelize options
const sequelize = new Sequelize(database, username, password, {
host : 'localhost',
dialect : 'mysql',
dialectOptions: {decimalNumbers: true}, // fix to ensure DECIMAL will not be stored as a string
logging : false,
pool : {
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);
module.exports = (mysqlConfig) => {
const { database, username, password } = mysqlConfig;
const db = {};
// set sequelize options
const sequelize = new Sequelize(database, username, password, {
host : 'localhost',
dialect : 'mysql',
dialectOptions: {decimalNumbers: true}, // fix to ensure DECIMAL will not be stored as a string
logging : false,
pool : {
max : 5,
min : 0,
idle : 10000,
acquire: 10000,
},
});
// manually add each model to the db
const Certificate = require('./certificate.js');
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);
// 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);
}
// establish mysql connection
sequelize
.authenticate()
.then(() => {
logger.info('Sequelize has established mysql connection successfully.');
})
.catch(function (error) {
logger.error(`${tableName}.upsert error`, error);
throw error;
.catch(err => {
logger.error('Sequelize was unable to connect to the database:', err);
});
};
// add a 'getTrendingFiles' method to the db object. note: change this to get claims directly. might need new association between Request and Claim
db.getTrendingFiles = (startDate) => {
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 });
};
// manually add each model to the db object
const Certificate = require('./certificate.js');
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": {
"test": "mocha --recursive",
"test-all": "mocha --recursive",
"start": "node server.js",
"start-dev": "nodemon server.js",
"start": "node index.js",
"start-dev": "nodemon index.js",
"lint": "eslint .",
"fix": "eslint . --fix",
"precommit": "eslint .",

View file

@ -9,7 +9,6 @@ const logger = require('winston');
const helmet = require('helmet');
const PORT = 3000; // set port
const app = express(); // create an Express application
const db = require('./models'); // require our models for syncing
const passport = require('passport');
const cookieSession = require('cookie-session');
@ -62,23 +61,34 @@ app.set('view engine', 'handlebars');
app.use(populateLocalsDotUser);
// start the server
db.sequelize
.sync() // sync sequelize
.then(() => { // require routes
require('./routes/auth-routes.js')(app);
require('./routes/api-routes.js')(app);
require('./routes/page-routes.js')(app);
require('./routes/serve-routes.js')(app);
require('./routes/fallback-routes.js')(app);
const http = require('http');
return http.Server(app);
})
.then(server => { // start the server
server.listen(PORT, () => {
logger.info('Trusting proxy?', app.get('trust proxy'));
logger.info(`Server is listening on PORT ${PORT}`);
const startServer = (mysqlConfig) => {
const db = require('./models')(mysqlConfig); // require our models for syncing
db.sequelize
// sync sequelize
.sync()
// require routes
.then(() => {
require('./routes/auth-routes.js')(app);
require('./routes/api-routes.js')(app);
require('./routes/page-routes.js')(app);
require('./routes/serve-routes.js')(app);
require('./routes/fallback-routes.js')(app);
const http = require('http');
return http.Server(app);
})
// 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,
},
externals: [nodeExternals()],
entry : ['babel-polyfill', 'whatwg-fetch', './index.js'],
entry : ['babel-polyfill', 'whatwg-fetch', './server.js'],
output : {
path : Path.join(__dirname, '/'),
publicPath: '/',
filename : 'server.js',
filename : 'index.js',
},
module: {
rules: [