Skip to content

Commit

Permalink
narrowed match campground lookup from API
Browse files Browse the repository at this point in the history
  • Loading branch information
bmarieay committed Mar 1, 2022
1 parent 0985381 commit 1809ecd
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 34 deletions.
46 changes: 22 additions & 24 deletions controllers/campgrounds.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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){
Expand Down Expand Up @@ -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({
Expand All @@ -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: {
Expand All @@ -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;
}

Expand Down Expand Up @@ -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) => {
Expand Down
14 changes: 4 additions & 10 deletions public/javascripts/pagination.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
}

Expand Down Expand Up @@ -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();
}
Expand Down Expand Up @@ -114,7 +107,7 @@ prevBtn.addEventListener('click', function() {

})

//next button
nextBtn.addEventListener('click', function() {
if(readCookie() < max){
paginationHandler.call(
Expand All @@ -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');
Expand Down

0 comments on commit 1809ecd

Please sign in to comment.