From 1809ecd7f0bb6eb00f7ae8fcd294d2d0549c1c6d Mon Sep 17 00:00:00 2001 From: bmarieay Date: Mon, 28 Feb 2022 20:40:24 -0800 Subject: [PATCH] narrowed match campground lookup from API --- controllers/campgrounds.js | 46 +++++++++++++++----------------- public/javascripts/pagination.js | 14 +++------- 2 files changed, 26 insertions(+), 34 deletions(-) diff --git a/controllers/campgrounds.js b/controllers/campgrounds.js index 70102e6..eca0417 100644 --- a/controllers/campgrounds.js +++ b/controllers/campgrounds.js @@ -6,7 +6,10 @@ const mapBoxToken = process.env.MAPBOX_TOKEN; const axios = require("axios"); const key = process.env.API_KEY; const geocoder = mbxGeocoding({ accessToken: mapBoxToken }); -//TODO: AFTER NEED TO REFACTOR ASYNCS TO MIDDLEWARE +/* +** TODO:IMPROVE ACCESSIBLITY +** AFTER NEED TO REFACTOR ASYNCS TO MIDDLEWARE +*/ //SETUP A COOKIE FOR SEARCH MODE mbxGeocoding({ accessToken: mapBoxToken }); const config = { @@ -40,7 +43,6 @@ module.exports.index = async (req, res) => { result.allItemsFetched = allCampgrounds.map( camp => camp).length; const max = Math.ceil(result.allItemsFetched / 20.0); let {page, limit, q} = req.query; - // console.log(q) page = parseInt(page); limit = parseInt(limit); if(!page || page < 0){ @@ -69,24 +71,23 @@ module.exports.index = async (req, res) => { } res.cookie('currentPage', page); - if(!q){//if there is no searching passed + if(!q){ + //if there is no filter passed just render all campgrounds res.clearCookie('filter'); const campgrounds = await Campground.find().limit(limit).skip(startIndex); result.results = campgrounds; - //for determining max number of pages return res.render('campgrounds/index', {result}); - // res.send(result); } - //user searched for something - const queried = await axios.get(`https://developer.nps.gov/api/v1/campgrounds?limit=15&stateCode=${q}`, config); + + //user filtered campgrounds + const queried = await axios.get(`https://developer.nps.gov/api/v1/campgrounds?limit=20&stateCode=${q}`, config); let matchedCampground; result.filter = q; if(queried.data.data.length) { //If found: save to database or just render if it already exists - //TODO: DO NOT BASE OFF OF THE FETCHED DATA BECAUSE IT HAS DIFFERENT JSON FORMAT FROM - //THE CAMPGROUND SCHEMA DEFINED const campPromises = queried.data.data.map(async function(camp) { - matchedCampground = await Campground.find({title: camp.name}); + //make a more narrow filter for matching + matchedCampground = await Campground.find({$and:[{title: camp.name},{description: camp.description}]}); if(camp.images[0]){ //make a new campground const campground = new Campground({ @@ -97,10 +98,9 @@ module.exports.index = async (req, res) => { title: camp.name, description: camp.description, - //assign a random price if there is no cost + //assign no price if there is no cost price: camp.fees[0] ? camp.fees[0].cost : 0, - images: camp.images.map(c => ({ url: c.url})), geometry: { @@ -115,18 +115,16 @@ module.exports.index = async (req, res) => { if(matchedCampground.length){ result.results.push(...matchedCampground); } else { - // await campground.save(); + await campground.save(); result.results.push(campground); } } - }); + await Promise.all(campPromises); + } else { - //do nothing if there is no result in api - //store empty object in result for rendering in index template - //store query for client use - // result.results = queried.data.data; + // NOTHING FOUND IN API result.query = q; } @@ -243,17 +241,17 @@ module.exports.editCampground = async (req, res) => { const {id} = req.params; //make this shorter later const campground = await Campground.findByIdAndUpdate(id, {...req.body.campground});//spread each properties - const imgs = req.files.map(f => ({ url: f.path, filename: f.filename })) - campground.images.push(...imgs) + const imgs = req.files.map(f => ({ url: f.path, filename: f.filename })); + campground.images.push(...imgs); await campground.save(); if(req.body.deleteImages){ for(let filename of req.body.deleteImages){ - await cloudinary.uploader.destroy(filename) + await cloudinary.uploader.destroy(filename); } - await campground.updateOne({$pull: {images: {filename: {$in: req.body.deleteImages}}}}) + await campground.updateOne({$pull: {images: {filename: {$in: req.body.deleteImages}}}}); } - req.flash('success', 'Successfully updated campground!') - res.redirect(`/campgrounds/${campground._id}`) + req.flash('success', 'Successfully updated campground!'); + res.redirect(`/campgrounds/${campground._id}`); } module.exports.deleteCampground = async (req, res) => { diff --git a/public/javascripts/pagination.js b/public/javascripts/pagination.js index c9140f2..59650f8 100644 --- a/public/javascripts/pagination.js +++ b/public/javascripts/pagination.js @@ -6,7 +6,7 @@ const nextContainer = document.querySelector('.next-btn'); let max = Math.ceil(resultLength / 20.0); console.log("max page:", max, " length result:", resultLength) //update total later according to data -//TODO: CHANGE MAX SO THAT IT WILL DYNAMICALLY ADJUST WHEN USER IS SEARCHING + const pageNumber = (total, max, current) => { const half = Math.round(max / 2); console.log("total:", total) @@ -28,20 +28,14 @@ const pageNumber = (total, max, current) => { } else { previousContainer.removeAttribute('tabindex'); previousContainer.classList.remove('disabled'); - // prevBtn.classList.remove('text-muted'); - } - // alert(current); - // alert(total); + if(current === total){ - // nextBtn.classList.add('text-muted'); - // nextBtn.removeAttribute('href'); nextContainer.classList.add('disabled') } else { nextContainer.classList.remove('disabled'); } - return Array.from({length: max}, (_, i) => (i + 1) + from) } @@ -75,7 +69,6 @@ function readCookie() { //calls the new list of pages function renderCorrectPages(currentPage){ //set the new page - // localStorage.setItem("currentPage", currentPage); document.cookie = `currentPage=${currentPage}`; initialize(); } @@ -114,7 +107,7 @@ prevBtn.addEventListener('click', function() { }) - +//next button nextBtn.addEventListener('click', function() { if(readCookie() < max){ paginationHandler.call( @@ -125,6 +118,7 @@ nextBtn.addEventListener('click', function() { } }) +//apply accent color to current page for(let button of pageButton){ if(parseInt(button.innerText) === readCookie()){ button.classList.add('active-btn');