0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2026-01-08 20:23:39 +00:00

linting and remove async conflict

This commit is contained in:
Víctor Losada Hernández
2024-05-07 10:14:46 +02:00
parent 40ac8b1909
commit f9f2e604c0
2 changed files with 353 additions and 295 deletions

View File

@@ -17,64 +17,46 @@ const BrewItem = require('../basePages/listPage/brewItem/brewItem.jsx');
const request = require('../../utils/request-middleware.js'); const request = require('../../utils/request-middleware.js');
const ArchivePage = createClass({ const ArchivePage = createClass({
displayName : 'ArchivePage', displayName: 'ArchivePage',
getDefaultProps : function () { getDefaultProps: function () {
return {}; return {};
}, },
getInitialState : function () { getInitialState: function () {
return { return {
//request //request
title : this.props.query.title || '', title: this.props.query.title || '',
//tags : {}, //tags : {},
legacy : `${this.props.query.legacy === 'false' ? false : true }`, legacy: `${this.props.query.legacy === 'false' ? false : true}`,
v3 : `${this.props.query.v3 === 'false' ? false : true }`, v3: `${this.props.query.v3 === 'false' ? false : true}`,
pageSize : this.props.query.size || 10, pageSize: this.props.query.size || 10,
page : parseInt(this.props.query.page) || 1, page: parseInt(this.props.query.page) || 1,
//response //response
brewCollection : null, brewCollection: null,
totalPages : null, totalPages: null,
totalBrews : null, totalBrews: null,
searching : false, searching: false,
error : null, error: null,
}; };
}, },
componentDidMount : function() { componentDidMount: function () {
if (this.state.title !== '') { if (this.state.title !== '') {
this.loadPage(this.state.page, false); this.loadPage(this.state.page, false);
} }
}, },
updateStateWithBrews : function (brews, page, totalPages, totalBrews) { updateStateWithBrews: function (brews, page, totalPages, totalBrews) {
this.setState({ this.setState({
brewCollection : brews || null, brewCollection: brews || null,
page : parseInt(page) || 1, page: parseInt(page) || 1,
totalPages : totalPages || 1, totalPages: totalPages || 1,
totalBrews : totalBrews, totalBrews: totalBrews,
searching : false searching: false,
}); });
}, },
updateStateWithForm : function() { updateUrl: function (title, page, size, v3, legacy) {
const title = document.getElementById( 'title' ).value || "";
const size = document.getElementById( 'size' ).value || 10;
const page = 1;
const v3 = document.getElementById('v3').checked;
const legacy = document.getElementById('legacy').checked;
this.setState({
title: title,
pageSize: size,
v3: v3,
legacy: legacy
});
this.updateUrl(title, page, size, v3, legacy);
},
updateUrl : function(title, page, size, v3, legacy) {
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);
@@ -91,45 +73,68 @@ const ArchivePage = createClass({
urlParams.set('v3', v3); urlParams.set('v3', v3);
urlParams.set('legacy', legacy); urlParams.set('legacy', legacy);
url.search = urlParams.toString(); // Convert URLSearchParams to string url.search = urlParams.toString(); // Convert URLSearchParams to string
window.history.replaceState(null, null, url); window.history.replaceState(null, null, url);
}, },
loadPage : async function(page, update) { loadPage: async function (page, update) {
if(update === true) { //load form data directly
this.updateStateWithForm(); const title = document.getElementById('title').value || '';
}; const size = document.getElementById('size').value || 10;
const v3 = document.getElementById('v3').checked;
const legacy = document.getElementById('legacy').checked;
// Update state with form data for later, only when first page
if (update === true) {
this.setState({
title: title,
pageSize: size,
v3: v3,
legacy: legacy,
});
this.updateUrl(title, page, size, v3, legacy);
}
if (title !== '') { if (title !== '') {
try { try {
this.setState({ searching: true, error: null }); this.setState({ searching: true, error: null });
const title = encodeURIComponent(this.state.title); await request
const size = parseInt(this.state.pageSize); .get(
const {legacy, v3} = this.state; `/api/archive?title=${title}&page=${page}&size=${size}&v3=${v3}&legacy=${legacy}`
await request.get(`/api/archive?title=${title}&page=${page}&size=${size}&v3=${v3}&legacy=${legacy}`) )
.then((response)=>{ .then((response) => {
if(response.ok) { if (response.ok) {
this.updateStateWithBrews(response.body.brews, page, response.body.totalPages, response.body.totalBrews); this.updateStateWithBrews(
response.body.brews,
page,
response.body.totalPages,
response.body.totalBrews
);
} }
}); });
} catch (error) { } catch (error) {
this.setState({ error: `${error.response.status}` }) this.setState({ error: `${error.response.status}` });
this.updateStateWithBrews([], 1, 1, 0); this.updateStateWithBrews([], 1, 1, 0);
} }
console.log(!this.state.brewCollection || brewCollection.length === 0); console.log('a',
if(!this.state.brewCollection) { !this.state.brewCollection || brewCollection.length === 0
this.setState({ error: '404'}); );
if (!this.state.brewCollection) {
this.setState({ error: '404' });
} }
} }
}, },
renderNavItems : function () { renderNavItems: function () {
return ( return (
<Navbar> <Navbar>
<Nav.section> <Nav.section>
<Nav.item className='brewTitle'>Archive: Search for brews</Nav.item> <Nav.item className="brewTitle">
Archive: Search for brews
</Nav.item>
</Nav.section> </Nav.section>
<Nav.section> <Nav.section>
<NewBrew /> <NewBrew />
@@ -141,40 +146,42 @@ const ArchivePage = createClass({
); );
}, },
renderForm : function () { renderForm: function () {
return ( return (
<div className='brewLookup'> <div className="brewLookup">
<h2 className='formTitle'>Brew Lookup</h2> <h2 className="formTitle">Brew Lookup</h2>
<div className="formContents"> <div className="formContents">
<label> <label>
Title of the brew Title of the brew
<input <input
id='title' id="title"
type='text' type="text"
name='title' name="title"
defaultValue={this.state.title} defaultValue={this.state.title}
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === 'Enter') { if (e.key === 'Enter') {
this.loadPage(1, true); this.loadPage(1, true);
} }
}} }}
placeholder='v3 Reference Document' placeholder="v3 Reference Document"
/> />
</label> </label>
<label> <label>
Results per page Results per page
<input <input
id='size' id="size"
type="number" type="number"
min="6"step="2"max="30" min="6"
step="2"
max="30"
name="pageSize" name="pageSize"
/> />
</label> </label>
<label> <label>
<input <input
id='v3' id="v3"
type="checkbox" type="checkbox"
defaultChecked={this.state.v3} defaultChecked={this.state.v3}
/> />
@@ -183,14 +190,13 @@ const ArchivePage = createClass({
<label> <label>
<input <input
id='legacy' id="legacy"
type="checkbox" type="checkbox"
defaultChecked={this.state.legacy} defaultChecked={this.state.legacy}
/> />
Search for legacy brews Search for legacy brews
</label> </label>
{/* In the future, we should be able to filter the results by adding tags. {/* In the future, we should be able to filter the results by adding tags.
<<StringArrayEditor label='tags' valuePatterns={[/^(?:(?:group|meta|system|type):)?[A-Za-z0-9][A-Za-z0-9 \/.\-]{0,40}$/]} <<StringArrayEditor label='tags' valuePatterns={[/^(?:(?:group|meta|system|type):)?[A-Za-z0-9][A-Za-z0-9 \/.\-]{0,40}$/]}
placeholder='add tag' unique={true} placeholder='add tag' unique={true}
@@ -201,15 +207,16 @@ const ArchivePage = createClass({
*/} */}
<button <button
className='search' className="search"
onClick={()=>{ onClick={() => {
this.loadPage(1, true); this.loadPage(1, true);
}}> }}
>
Search Search
<i <i
className={cx('fas', { className={cx('fas', {
'fa-search' : !this.state.searching, 'fa-search': !this.state.searching,
'fa-spin fa-spinner' : this.state.searching, 'fa-spin fa-spinner': this.state.searching,
})} })}
/> />
</button> </button>
@@ -221,12 +228,24 @@ const ArchivePage = createClass({
renderPaginationControls() { renderPaginationControls() {
const title = encodeURIComponent(this.state.title); const title = encodeURIComponent(this.state.title);
const size = parseInt(this.state.pageSize); const size = parseInt(this.state.pageSize);
const {page, totalPages, legacy, v3} = this.state; const { page, totalPages, legacy, v3 } = this.state;
const pages = new Array(totalPages).fill().map((_, index) => ( const pages = new Array(totalPages).fill().map((_, index) => (
<a key={index} className={`pageNumber ${page == index + 1 ? 'currentPage' : ''}`} href={`/archive?title=${title}&page=${index+1}&size=${size}&v3=${v3}&legacy=${legacy}`}>{index + 1}</a> <a
key={index}
className={`pageNumber ${
page == index + 1 ? 'currentPage' : ''
}`}
href={`/archive?title=${title}&page=${
index + 1
}&size=${size}&v3=${v3}&legacy=${legacy}`}
>
{index + 1}
</a>
)); ));
if(totalPages === null) {return;} if (totalPages === null) {
return;
}
return ( return (
<div className="paginationControls"> <div className="paginationControls">
@@ -238,9 +257,12 @@ const ArchivePage = createClass({
&lt;&lt; &lt;&lt;
</button> </button>
)} )}
<ol className='pages'>{pages}</ol> <ol className="pages">{pages}</ol>
{page < totalPages && ( {page < totalPages && (
<button className="nextPage" onClick={() => this.loadPage(page + 1, false)}> <button
className="nextPage"
onClick={() => this.loadPage(page + 1, false)}
>
&gt;&gt; &gt;&gt;
</button> </button>
)} )}
@@ -249,20 +271,26 @@ const ArchivePage = createClass({
}, },
renderFoundBrews() { renderFoundBrews() {
console.log('State when rendering:');
console.table(this.state); console.table(this.state);
const { title, brewCollection, page, totalPages, error, searching } = this.state; const { title, brewCollection, page, totalPages, error, searching } =
this.state;
if(searching) { if (searching) {
return ( return (
<div className='foundBrews searching'> <div className="foundBrews searching">
<h3 className='searchAnim'>Searching</h3> <h3 className="searchAnim">Searching</h3>
</div> </div>
); );
}; }
if (title === '') {
return (
if(title === '') {return (<div className='foundBrews noBrews'><h3>Whenever you want, just start typing...</h3></div>);} <div className="foundBrews noBrews">
<h3>Whenever you want, just start typing...</h3>
</div>
);
}
if (error) { if (error) {
console.log('render Error: ', error); console.log('render Error: ', error);
@@ -272,55 +300,64 @@ const ArchivePage = createClass({
errorMessage = "404 - We didn't find any brew"; errorMessage = "404 - We didn't find any brew";
break; break;
case '503': case '503':
errorMessage = ' 503 - Your search is not specific enough. Too many brews meet this criteria for us to display them.'; errorMessage =
' 503 - Your search is not specific enough. Too many brews meet this criteria for us to display them.';
break; break;
case '500': case '500':
errorMessage = "500 - We don't know what happened." errorMessage = "500 - We don't know what happened.";
default: default:
errorMessage = 'An unexpected error occurred'; errorMessage = 'An unexpected error occurred';
} }
return ( return (
<div className='foundBrews noBrews'> <div className="foundBrews noBrews">
<h3>Error: {errorMessage}</h3> <h3>Error: {errorMessage}</h3>
</div> </div>
); );
}; }
if (!brewCollection || brewCollection.length === 0) { if (!brewCollection || brewCollection.length === 0) {
return ( return (
<div className='foundBrews noBrews'> <div className="foundBrews noBrews">
<h3>No brews found</h3> <h3>No brews found</h3>
</div> </div>
); );
}; }
return ( return (
<div className='foundBrews'> <div className="foundBrews">
<span className='totalBrews'>Brews found: {this.state.totalBrews}</span> <span className="totalBrews">
{brewCollection.map((brew, index)=>( Brews found: {this.state.totalBrews}
<BrewItem brew={brew} key={index} reportError={this.props.reportError} /> </span>
{brewCollection.map((brew, index) => (
<BrewItem
brew={brew}
key={index}
reportError={this.props.reportError}
/>
))} ))}
{this.renderPaginationControls()} {this.renderPaginationControls()}
</div> </div>
); );
}, },
render : function () { render: function () {
return ( return (
<div className='archivePage'> <div className="archivePage">
<link href='/themes/V3/Blank/style.css' rel='stylesheet'/> <link href="/themes/V3/Blank/style.css" rel="stylesheet" />
<link href='/themes/V3/5ePHB/style.css' rel='stylesheet'/> <link href="/themes/V3/5ePHB/style.css" rel="stylesheet" />
{this.renderNavItems()} {this.renderNavItems()}
<div className='content'> <div className="content">
<div className='welcome'> <div className="welcome">
<h1>Welcome to the Archive</h1> <h1>Welcome to the Archive</h1>
</div> </div>
<div className='flexGroup'> <div className="flexGroup">
<div className='form dataGroup'>{this.renderForm()}</div> <div className="form dataGroup">
<div className='resultsContainer dataGroup'> {this.renderForm()}
<div className='title'> </div>
<div className="resultsContainer dataGroup">
<div className="title">
<h2>Your results, my lordship</h2> <h2>Your results, my lordship</h2>
</div> </div>
{this.renderFoundBrews()} {this.renderFoundBrews()}

View File

@@ -8,12 +8,18 @@ const archive = {
findBrews: async (req, res, next) => { findBrews: async (req, res, next) => {
try { try {
/* /*
//log db name and collection name, for local purposes
const dbName = HomebrewModel.db.name; const dbName = HomebrewModel.db.name;
console.log("Database Name:", dbName); console.log("Database Name:", dbName);
const collectionName = HomebrewModel.collection.name; const collectionName = HomebrewModel.collection.name;
console.log("Collection Name:", collectionName); console.log("Collection Name:", collectionName);
*/ */
const bright = '\x1b[1m'; // Bright (bold) style
const yellow = '\x1b[93m'; // yellow color
const reset = '\x1b[0m'; // Reset to default style
console.log(`Query as received in ${bright + yellow}archive api${reset}:`);
console.table(req.query); console.table(req.query);
const title = req.query.title || ''; const title = req.query.title || '';
@@ -88,11 +94,26 @@ const archive = {
return res.json({ brews, page, totalPages, totalBrews }); return res.json({ brews, page, totalPages, totalBrews });
} catch (error) { } catch (error) {
console.error(error); console.error(error);
console.log('error status number: ', error.response.status);
if (error.response && error.response.status === 503) { if (error.response && error.response.status) {
return res const status = error.response.status;
.status(503)
.json({ errorCode: '503', message: 'Service Unavailable' }); if (status === 500) {
return res.status(500).json({
errorCode: '500',
message: 'Internal Server Error',
});
} else if (status === 503) {
return res.status(503).json({
errorCode: '503',
message: 'Service Unavailable',
});
} else {
return res.status(status).json({
errorCode: status.toString(),
message: 'Internal Server Error',
});
}
} else { } else {
return res.status(500).json({ return res.status(500).json({
errorCode: '500', errorCode: '500',