Skip to content

Commit

Permalink
temporarily removed pagination in search mode
Browse files Browse the repository at this point in the history
  • Loading branch information
bmarieay committed Feb 28, 2022
1 parent 792374f commit 8a49186
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 62 deletions.
105 changes: 51 additions & 54 deletions controllers/campgrounds.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,30 @@ const axios = require("axios");
const key = process.env.API_KEY;
const geocoder = mbxGeocoding({ accessToken: mapBoxToken });
//TODO: AFTER NEED TO REFACTOR ASYNCS TO MIDDLEWARE
//SETUP A COOKIE FOR SEARCH MODE
mbxGeocoding({ accessToken: mapBoxToken });
const config = {
params:
{
api_key : key
}
};
const reverseGeo = async (coordinates) => {
try {
const geoData = await geocoder.reverseGeocode({
query: coordinates,
limit: 1
}).send()

if(geoData.body.features[0]){
return geoData.body.features[0].text;
} else{
return 'NO LOCATION'
}
} catch (error) {
console.log("ERROR!:", error)
}
}

//TODO: MAKE A MIDDLEWARE FOR RENDERING INDEX
module.exports.index = async (req, res) => {
Expand All @@ -23,8 +40,13 @@ 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;
if(!q){//if there is no searching passed
page = parseInt(page);
// console.log(q)
if(!q){
res.clearCookie('filter');
} else {
res.cookie('filter', q)
}
page = parseInt(page);
limit = parseInt(limit);
if(!page || page < 0){
page=1;//very first page
Expand All @@ -37,7 +59,6 @@ module.exports.index = async (req, res) => {
}
const startIndex = (page - 1) * limit;
const endIndex = page * limit;
const campgrounds = await Campground.find().limit(limit).skip(startIndex);
//get info for the pagination(prev and next)
if(startIndex > 0){
result.previous = {
Expand All @@ -52,28 +73,25 @@ module.exports.index = async (req, res) => {
}
}
res.cookie('currentPage', page);

if(!q){//if there is no searching passed
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=3&q=${q}`, config);
let matchedCampground;
if(!queried.data.data.length){
//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;
result.query = q;
return res.render('campgrounds/index', {result})
} else {
// res.cookie('filter', q);
const queried = await axios.get(`https://developer.nps.gov/api/v1/campgrounds?limit=15&stateCode=${q}`, config);
let matchedCampground;
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});
if(!matchedCampground.length && camp.images[0]){
if(camp.images[0]){
//make a new campground
const campground = new Campground({
location: camp.addresses[0] ?
Expand All @@ -84,7 +102,7 @@ module.exports.index = async (req, res) => {

description: camp.description,
//assign a random price if there is no cost
price: camp.fees[0] ? camp.fees[0].cost : price,
price: camp.fees[0] ? camp.fees[0].cost : 0,


images: camp.images.map(c => ({ url: c.url})),
Expand All @@ -98,49 +116,28 @@ module.exports.index = async (req, res) => {
}
})
//NOTE:decide if need to save later
// await campground.save();
result.results.push(campground);
} else {
//MATCH FOUND
result.results.push(camp);
if(matchedCampground.length){
result.results.push(...matchedCampground);
} else {
// 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;
result.query = q;
}
// queried.data.data.forEach( async (camp, i) => {
// if(camp.images[0] && camp.name){
// const price = Math.floor(Math.random() * 20) + 10;
// const campground = new Campground({
// //do reverse lookup here!!!!!from the coordinates if no address available
// location: camp.addresses[0] ?
// `${camp.addresses[0].line1} ${camp.addresses[0].city} ${camp.addresses[0].stateCode}`:
// await reverseGeo([Number.parseFloat( camp.longitude, 10), Number.parseFloat( camp.latitude, 10)]),

// title: camp.name,

// description: camp.description,
// //assign a random price if there is no cost
// price: camp.fees[0] ? camp.fees[0].cost : price,

// geometry: {
// type: 'Point',
// coordinates: [
// camp.longitude,
// camp.latitude
// ]
// }
// })
// await upload(camp.images.map(img => img.url), campground);
// await User.findByIdAndUpdate(mainAuth, {$push:{campgrounds: campground}});
// //add cloud uploader for below. use only and save if campground not yet in database otherwise just show it
// if(campground.success !== 'fail') {
// await campground.save();
// }
// result.results.push()
// }
// })
// res.render('campgrounds/index', {result});
res.send(result);
const {filter} = req.cookies;
result.filter = filter;
console.log(result)
// res.send(result);
res.render('campgrounds/index', {result})
}

module.exports.renderNewForm = (req, res) => {
Expand Down
11 changes: 5 additions & 6 deletions public/javascripts/pagination.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +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 Down Expand Up @@ -56,21 +57,20 @@ function initialize (){


function readCookie() {
var allcookies = document.cookie;
let allcookies = document.cookie;
let key, value;

// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');

// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++) {
for(let i=0; i<cookiearray.length; i++) {
key = cookiearray[i].split('=')[0];
if(key === 'currentPage'){
value = parseInt(cookiearray[i].split('=')[1]);
}
}
return value;
}
}

//calls the new list of pages
function renderCorrectPages(currentPage){
Expand Down Expand Up @@ -130,5 +130,4 @@ for(let button of pageButton){
button.classList.add('active-btn');
break;
}
}

}
4 changes: 4 additions & 0 deletions public/stylesheets/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,10 @@
border-color: var(--univ-light);
}

.form-select{
width: max-content;
}

#map, #cluster-map{
width: 100%;
}
Expand Down
59 changes: 57 additions & 2 deletions views/campgrounds/index.ejs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<% layout('layouts/boilerplate') %>
<div id="cluster-map" class="border border-dark"></div>

<% if(result.results.length) {%>
<% if(result.results.length && !result.filter.length) {%>
<h1 class="title">All Campgrounds</h1>
<nav aria-label="Campgrounds navigation pages" class="fw-bold">
<ul class="pagination pagination-sm d-flex justify-content-center">
Expand All @@ -16,6 +16,61 @@
</nav>
<% } %>

<form action="/campgrounds">
<select class="form-select" name="q" aria-label="Default select example" onchange="this.form.submit()">
<option selected>Select a state</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
</form>

<div class="gutter">
<a href="/campgrounds/new" class="accent">Add Campground</a>
Expand All @@ -33,7 +88,6 @@
<img class="img-fluid" src="https://res.cloudinary.com/maranttt/image/upload/v1643679209/YelpCamp/nhzmrsjscjzcll52hpod.jpg" alt="">
<% } %>
</div>
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title"><a href="/campgrounds/<%= campground._id %>" class="accent"><%= campground.title %></a></h5>
Expand All @@ -60,6 +114,7 @@
const campgrounds = {features: <%- JSON.stringify(result.results) %>};
const resultLength = <%-result.allItemsFetched %>;
</script>
<noscript><input type=”submit” value=”Submit”></noscript>

<script src="/javascripts/clusterMap.js"></script>
<script src="/javascripts/pagination.js"></script>

0 comments on commit 8a49186

Please sign in to comment.