0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2025-12-28 17:52:38 +00:00

trying to figure out pagination

This commit is contained in:
Víctor Losada Hernández
2024-02-10 16:41:39 +01:00
parent 46d1f89b77
commit fe449abb47
2 changed files with 96 additions and 80 deletions

View File

@@ -24,85 +24,95 @@ const ArchivePage = createClass({
return { return {
title : this.props.query.title || '', title : this.props.query.title || '',
brewCollection : null, brewCollection : null,
page : 1,
totalPages : 1,
searching : false, searching : false,
error : null, error : null,
limit : '',
}; };
}, },
componentDidMount : function() { componentDidMount : function() {
this.lookup(); this.loadPage(1);
}, },
handleChange(e) { handleChange(e) {
this.setState({ title: e.target.value }); this.setState({ title: e.target.value });
}, },
lookup() {
this.setState({ searching: true, error: null }); updateStateWithBrews : (brews, page, totalPages) => {
request this.setState({
.get(`/archive/${this.state.title}`) brewCollection: brews,
.then((res) => this.setState({ brewCollection: res.body.brews }, this.setState({ limit: res.body.message}, this.setState({ error: null})))) page: page,
.catch((err) => this.setState({ error: err })) totalPages: totalPages,
.finally(() => this.setState({ searching: false })); searching: false
});
},
loadPage: async function(pageNumber) {
try {
this.updateUrl();
this.setState({ searching: true, error: null });
const title = encodeURIComponent(this.state.title);
const response = await fetch(`/archive?title=${title}&page=${pageNumber}`);
if (response.ok) {
const res = await response.json();
this.updateStateWithBrews(res.brews, pageNumber, res.totalPages);
}
} catch (error) {
console.log("LoadPage error: " + error);
}
}, },
updateUrl: function() { updateUrl: function() {
const url = new URL(window.location.href); const url = new URL(window.location.href);
const urlParams = new URLSearchParams(url.search); const urlParams = new URLSearchParams(url.search);
// Clear existing parameters
urlParams.delete('sort');
urlParams.delete('dir');
urlParams.delete('filter');
// Set the pathname to '/archive/?query' // Set the title and page parameters
urlParams.set('title', this.state.title); urlParams.set('title', this.state.title);
urlParams.set('page', this.state.page);
url.search = urlParams; url.search = urlParams.toString(); // Convert URLSearchParams to string
window.history.replaceState(null, null, url); window.history.replaceState(null, null, url);
}, },
renderFoundBrews() { renderFoundBrews() {
const brews = this.state.brewCollection; const { title, brewCollection, page, totalPages, error } = this.state;
console.log('brews: ',brews);
if (this.state.title == '') { if (title === '') {return (<div className="foundBrews noBrews"><h3>Whenever you want, just start typing...</h3></div>);}
return(
<div className="foundBrews noBrews">
<h3>Whenever you want, just start typing...</h3>
</div>
);
}
if (this.state.error !== null) { if (error !== null) { return (
return(
<div className="foundBrews noBrews"> <div className="foundBrews noBrews">
<div> <div><h3>I'm sorry, your request didn't work</h3>
<h3>I'm sorry, your request didn't work</h3> <br /><p>Your search is not specific enough. Too many brews meet this criteria for us to display them.</p>
<br /> </div></div>
<p>Your search is not enough specific, too many brews meet this criteria for us to forward them.</p> );}
if (!brewCollection || brewCollection.length === 0) { return (
<div className="foundBrews noBrews">
<h3>We haven't found brews meeting your request.</h3>
</div>
);}
return (
<div className="foundBrews">
<span className="brewCount">{`Brews Found: ${brewCollection.length}`}</span>
{brewCollection.map((brew, index) => (
<BrewItem brew={brew} key={index} reportError={this.props.reportError} />
))}
<div className="paginationControls">
{page > 1 && (
<button onClick={() => this.loadPage(page - 1)}>Previous Page</button>
)}
<span className="currentPage">Page {page}</span>
{page < totalPages && (
<button onClick={() => this.loadPage(page + 1)}>Next Page</button>
)}
</div> </div>
</div> </div>
); );
}
if (!brews || brews.length === 0) {
return(
<div className="foundBrews noBrews">
<h3>We haven't found brews meeting your request.</h3>
</div>
);
}
this.updateUrl();
return <div className="foundBrews">
<span className="brewCount">{brews.length} Brews Found</span>
<span className="limit">{this.state.limit}</span>
{brews.map((brew, index) => (
<BrewItem brew={brew} key={index} reportError={this.props.reportError}/>
))}
</div>
}, },
renderForm: function () { renderForm: function () {
return ( return (
<div className='brewLookup'> <div className='brewLookup'>
@@ -115,7 +125,7 @@ const ArchivePage = createClass({
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === 'Enter') { if (e.key === 'Enter') {
this.handleChange(e); this.handleChange(e);
this.lookup(); this.loadPage(1);
} }
}} }}
placeholder='v3 Reference Document' placeholder='v3 Reference Document'
@@ -125,7 +135,7 @@ const ArchivePage = createClass({
<input type="checkbox" id="v3" /><label>v3 only</label> <input type="checkbox" id="v3" /><label>v3 only</label>
*/} */}
<button onClick={() => { this.handleChange({ target: { value: this.state.title } }); this.lookup(); }}> <button onClick={() => { this.handleChange({ target: { value: this.state.title } }); this.loadPage(1); }}>
<i <i
className={cx('fas', { className={cx('fas', {
'fa-search': !this.state.searching, 'fa-search': !this.state.searching,

View File

@@ -7,40 +7,46 @@ const archive = {
/* Searches for matching title, also attempts to partial match */ /* Searches for matching title, also attempts to partial match */
findBrews: async (req, res, next) => { findBrews: async (req, res, next) => {
try { try {
const limit = 1000; const page = parseInt(req.params.page) || 1;
const brews = await HomebrewModel.find({ console.log('try:',page);
title: { $regex: req.params.query, $options: 'i' }, const pageSize = 10; // Set a default page size
const skip = (page - 1) * pageSize;
const title = {
title: { $regex: decodeURIComponent(req.params.title), $options: 'i' },
published: true published: true
}, };
{
editId:0, const projection = {
googleId:0, editId: 0,
text:0, googleId: 0,
textBin:0, text: 0,
}) textBin: 0,
.limit(limit) };
.maxTimeMS(10000)
.exec(); const brews = await HomebrewModel.find(title, projection)
.skip(skip)
.limit(pageSize)
.maxTimeMS(5000)
.exec();
if (!brews || brews.length === 0) { if (!brews || brews.length === 0) {
// No published documents found with the given title // No published documents found with the given title
return res.status(404).json({ error: 'Published documents not found' }); return res.status(404).json({ error: 'Published documents not found' });
} }
let message = ''; const totalDocuments = await HomebrewModel.countDocuments(title);
if (brews.length === limit) {
// If the limit has been reached, include a message in the response
message = `You've reached the limit of ${limit} documents, you can try being more specific in your search.`;
}
return res.json({ brews, message }); const totalPages = Math.ceil(totalDocuments / pageSize);
return res.json({ brews, page, totalPages});
} catch (error) { } catch (error) {
console.error(error); console.error(error);
return res.status(500).json({ error: 'Internal Server Error' }); return res.status(500).json({ error: 'Internal Server Error' });
} }
} }
} };
router.get('/archive/:query', asyncHandler(archive.findBrews)); router.get('/archive/:title/:page', asyncHandler(archive.findBrews));
module.exports = router; module.exports = router;