1
0
mirror of https://github.com/stolksdorf/homebrewery.git synced 2025-12-15 21:35:56 +00:00

added the search api with pagnination, and added a remove invalid brew endpoint to the admin

This commit is contained in:
Scott Tolksdorf
2016-04-20 01:02:44 -04:00
parent 8688b99bdf
commit f35950c2c4
5 changed files with 162 additions and 98 deletions

View File

@@ -5,49 +5,99 @@ var request = require('superagent');
var Moment = require('moment'); var Moment = require('moment');
//TODO: Add incremental React scrolling
var VIEW_LIMIT = 30;
var COLUMN_HEIGHT = 52;
var HomebrewAdmin = React.createClass({ var HomebrewAdmin = React.createClass({
getDefaultProps: function() { getDefaultProps: function() {
return { return {
homebrews : [],
admin_key : '' admin_key : ''
}; };
}, },
getInitialState: function() { getInitialState: function() {
return { return {
viewStartIndex: 0 page: 0,
count : 20,
brewCache : {},
total : 0,
processingOldBrews : false
}; };
}, },
clearOldBrews : function(){
if(!confirm("Are you sure you want to clear out old brews?")) return;
request.get('/homebrew/clear_old/?admin_key=' + this.props.admin_key) fetchBrews : function(page){
.send() request.get('/homebrew/api/search')
.end(function(err, res){ .query({
window.location.reload(); admin_key : this.props.admin_key,
count : this.state.count,
page : page
})
.end((err, res)=>{
this.state.brewCache[page] = res.body.brews;
this.setState({
brewCache : this.state.brewCache,
total : res.body.total,
count : res.body.count
})
}) })
}, },
componentDidMount: function() {
this.fetchBrews(this.state.page);
},
changePageTo : function(page){
if(!this.state.brewCache[page]){
this.fetchBrews(page);
}
this.setState({
page : page
})
},
clearInvalidBrews : function(){
request.get('/homebrew/api/invalid')
.query({admin_key : this.props.admin_key})
.end((err, res)=>{
if(!confirm("This will remove " + res.body.count + " brews. Are you sure?")) return;
request.get('/homebrew/api/invalid')
.query({admin_key : this.props.admin_key, do_it : true})
.end((err, res)=>{
alert("Done!")
});
});
},
deleteBrew : function(brewId){ deleteBrew : function(brewId){
request.get('/homebrew/remove/' + brewId +'?admin_key=' + this.props.admin_key) if(!confirm("Are you sure you want to delete '" + brewId + "'?")) return;
.send() request.get('/homebrew/api/remove/' + brewId)
.query({admin_key : this.props.admin_key})
.end(function(err, res){ .end(function(err, res){
window.location.reload(); window.location.reload();
}) })
}, },
renderBrews : function(){ handlePageChange : function(dir){
// return _.times(VIEW_LIMIT, (i)=>{ this.changePageTo(this.state.page + dir);
// var brew = this.props.homebrews[i + this.state.viewStartIndex]; },
// if(!brew) return null;
return _.map(this.props.homebrews, (brew)=>{ renderPagnination : function(){
var outOf;
if(this.state.total){
outOf = this.state.page + ' / ' + Math.round(this.state.total/this.state.count);
}
return <div className='pagnination'>
<i className='fa fa-chevron-left' onClick={this.handlePageChange.bind(this, -1)}/>
{outOf}
<i className='fa fa-chevron-right' onClick={this.handlePageChange.bind(this, 1)}/>
</div>
},
renderBrews : function(){
var brews = this.state.brewCache[this.state.page] || _.times(this.state.count);
return _.map(brews, (brew)=>{
return <tr className={cx('brewRow', {'isEmpty' : brew.text == "false"})} key={brew.sharedId}> return <tr className={cx('brewRow', {'isEmpty' : brew.text == "false"})} key={brew.sharedId}>
<td><a href={'/homebrew/edit/' + brew.editId} target='_blank'>{brew.editId}</a></td> <td><a href={'/homebrew/edit/' + brew.editId} target='_blank'>{brew.editId}</a></td>
<td><a href={'/homebrew/share/' + brew.shareId} target='_blank'>{brew.shareId}</a></td> <td><a href={'/homebrew/share/' + brew.shareId} target='_blank'>{brew.shareId}</a></td>
@@ -74,7 +124,7 @@ var HomebrewAdmin = React.createClass({
<th>Created At</th> <th>Created At</th>
<th>Last Updated</th> <th>Last Updated</th>
<th>Last Viewed</th> <th>Last Viewed</th>
<th>Number of Views</th> <th>Views</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -88,12 +138,14 @@ var HomebrewAdmin = React.createClass({
var self = this; var self = this;
return <div className='homebrewAdmin'> return <div className='homebrewAdmin'>
<h2> <h2>
Homebrews - {this.props.homebrews.length} Homebrews - {this.state.total}
<button className='clearOldButton' onClick={this.clearOldBrews}>
Clear Old
</button>
</h2> </h2>
{this.renderPagnination()}
{this.renderBrewTable()} {this.renderBrewTable()}
<button className='clearOldButton' onClick={this.clearInvalidBrews}>
Clear Old
</button>
</div> </div>
} }
}); });

View File

@@ -1,8 +1,7 @@
.homebrewAdmin{ .homebrewAdmin{
margin-bottom: 80px;
.brewTable{ .brewTable{
overflow-y : scroll;
max-height : 500px;
table{ table{
th{ th{

View File

@@ -43,7 +43,7 @@ var Statusbar = React.createClass({
if(!confirm("are you sure you want to delete this brew?")) return; if(!confirm("are you sure you want to delete this brew?")) return;
if(!confirm("are you REALLY sure? You will not be able to recover it")) return; if(!confirm("are you REALLY sure? You will not be able to recover it")) return;
request.get('/homebrew/remove/' + this.props.editId) request.get('/homebrew/api/remove/' + this.props.editId)
.send() .send()
.end(function(err, res){ .end(function(err, res){
window.location.href = '/homebrew'; window.location.href = '/homebrew';

View File

@@ -8,9 +8,6 @@ var app = express();
app.use(express.static(__dirname + '/build')); app.use(express.static(__dirname + '/build'));
app.use(bodyParser.json()); app.use(bodyParser.json());
//Mongoose //Mongoose
var mongoose = require('mongoose'); var mongoose = require('mongoose');
var mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/naturalcrit'; var mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/naturalcrit';
@@ -19,54 +16,32 @@ mongoose.connection.on('error', function(){
console.log(">>>ERROR: Run Mongodb.exe ya goof!"); console.log(">>>ERROR: Run Mongodb.exe ya goof!");
}); });
//Admin route //Admin route
process.env.ADMIN_USER = process.env.ADMIN_USER || 'admin'; process.env.ADMIN_USER = process.env.ADMIN_USER || 'admin';
process.env.ADMIN_PASS = process.env.ADMIN_PASS || 'password'; process.env.ADMIN_PASS = process.env.ADMIN_PASS || 'password';
process.env.ADMIN_KEY = process.env.ADMIN_KEY || 'admin_key'; process.env.ADMIN_KEY = process.env.ADMIN_KEY || 'admin_key';
var auth = require('basic-auth'); var auth = require('basic-auth');
//var HomebrewModel = require('./server/homebrew.model.js').model;
app.get('/admin', function(req, res){ app.get('/admin', function(req, res){
var credentials = auth(req) var credentials = auth(req)
if (!credentials || credentials.name !== process.env.ADMIN_USER || credentials.pass !== process.env.ADMIN_PASS) { if (!credentials || credentials.name !== process.env.ADMIN_USER || credentials.pass !== process.env.ADMIN_PASS) {
res.setHeader('WWW-Authenticate', 'Basic realm="example"') res.setHeader('WWW-Authenticate', 'Basic realm="example"')
return res.status(401).send('Access denied') return res.status(401).send('Access denied')
} }
vitreumRender({
/* page: './build/admin/bundle.dot',
HomebrewModel.find({}, function(err, homebrews){ prerenderWith : './client/admin/admin.jsx',
clearRequireCache : !process.env.PRODUCTION,
//Remove the text to reduce the response payload initialProps: {
homebrews = _.map(homebrews, (brew)=>{ url: req.originalUrl,
brew.text = brew.text != ''; admin_key : process.env.ADMIN_KEY,
return brew; },
}); }, function (err, page) {
return res.send(page)
console.log("HOMEBREW", homebrews.length); });
*/
vitreumRender({
page: './build/admin/bundle.dot',
prerenderWith : './client/admin/admin.jsx',
clearRequireCache : true,
initialProps: {
url: req.originalUrl,
admin_key : process.env.ADMIN_KEY,
//homebrews : homebrews,
},
}, function (err, page) {
return res.send(page)
});
// });
}); });
//Populate homebrew routes
app = require('./server/homebrew.api.js')(app); app = require('./server/homebrew.api.js')(app);
app = require('./server/homebrew.server.js')(app); app = require('./server/homebrew.server.js')(app);
@@ -75,14 +50,12 @@ app = require('./server/homebrew.server.js')(app);
app.get('*', function (req, res) { app.get('*', function (req, res) {
vitreumRender({ vitreumRender({
page: './build/naturalCrit/bundle.dot', page: './build/naturalCrit/bundle.dot',
globals:{ globals:{},
},
prerenderWith : './client/naturalCrit/naturalCrit.jsx', prerenderWith : './client/naturalCrit/naturalCrit.jsx',
initialProps: { initialProps: {
url: req.originalUrl url: req.originalUrl
}, },
clearRequireCache : true, clearRequireCache : !process.env.PRODUCTION,
}, function (err, page) { }, function (err, page) {
return res.send(page) return res.send(page)
}); });

View File

@@ -2,7 +2,23 @@ var _ = require('lodash');
var Moment = require('moment'); var Moment = require('moment');
var HomebrewModel = require('./homebrew.model.js').model; var HomebrewModel = require('./homebrew.model.js').model;
var changelogText = require('fs').readFileSync('./changelog.md', 'utf8'); var homebrewTotal = 0;
var refreshCount = function(){
HomebrewModel.count({}, function(err, total){
homebrewTotal = total;
});
};
refreshCount()
var mw = {
adminOnly : function(req, res, next){
if(req.query && req.query.admin_key == process.env.ADMIN_KEY){
next();
}else{
return res.status(401).send('Access denied');
}
}
};
var getTopBrews = function(cb){ var getTopBrews = function(cb){
@@ -12,7 +28,6 @@ var getTopBrews = function(cb){
} }
module.exports = function(app){ module.exports = function(app){
app.get('/homebrew/top', function(req, res){ app.get('/homebrew/top', function(req, res){
@@ -21,7 +36,6 @@ module.exports = function(app){
}); });
}) })
//Updating
app.put('/homebrew/update/:id', function(req, res){ app.put('/homebrew/update/:id', function(req, res){
HomebrewModel.find({editId : req.params.id}, function(err, objs){ HomebrewModel.find({editId : req.params.id}, function(err, objs){
if(!objs.length || err) return res.status(404).send("Can not find homebrew with that id"); if(!objs.length || err) return res.status(404).send("Can not find homebrew with that id");
@@ -35,39 +49,65 @@ module.exports = function(app){
}); });
}); });
app.get('/homebrew/remove/:id', function(req, res){ app.get('/homebrew/api/remove/:id', function(req, res){
//if(req.query && req.query.admin_key == process.env.ADMIN_KEY){ HomebrewModel.find({editId : req.params.id}, function(err, objs){
HomebrewModel.find({editId : req.params.id}, function(err, objs){ if(!objs.length || err) return res.status(404).send("Can not find homebrew with that id");
console.log(err); var resEntry = objs[0];
if(!objs.length || err) return res.status(404).send("Can not find homebrew with that id"); resEntry.remove(function(err){
var resEntry = objs[0]; if(err) return res.status(500).send("Error while removing");
resEntry.remove(function(err){ return res.status(200).send();
if(err) return res.status(500).send("Error while removing"); })
return res.status(200).send(); });
})
});
//}else{
// return res.status(401).send('Access denied');
//}
}); });
//Removes all empty brews that are older than 3 days //Removes all empty brews that are older than 3 days and that are shorter than a tweet
app.get('/homebrew/clear_old', function(req, res){ app.get('/homebrew/api/invalid', mw.adminOnly, function(req, res){
if(req.query && req.query.admin_key == process.env.ADMIN_KEY){ var invalidBrewQuery = HomebrewModel.find({
HomebrewModel.remove({ '$where' : "this.text.length < 140",
text : '', createdAt: {
createdAt: { $lt: Moment().subtract(3, 'days').toDate()
$lt: Moment().subtract(3, 'days').toDate() }
} });
}, function(err, objs){
return res.status(200).send(); if(req.query.do_it){
}); invalidBrewQuery.remove().exec((err, objs)=>{
refreshCount();
return res.send(200);
})
}else{ }else{
return res.status(401).send('Access denied'); invalidBrewQuery.exec((err, objs)=>{
if(err) console.log(err);
return res.json({
count : objs.length
})
})
} }
}); });
app.get('/homebrew/api/search', mw.adminOnly, function(req, res){
var page = req.query.page || 0;
var count = req.query.count || 20;
HomebrewModel.find({}, {
text : 0 //omit the text
}, {
skip: page*count,
limit: count*1
}, function(err, objs){
if(err) console.log(err);
return res.json({
page : page,
count : count,
total : homebrewTotal,
brews : objs
});
});
})
return app; return app;
} }