samedi 29 septembre 2018

If/Else Bootstrap Pagnation Rule only work on root URL (Express JS / Bootstrap)

The issue

This code works perfectly when visiting Page 1 (first page) and Page 574 (last page), it will block the Previous and Next Buttons to show the start/end of the pagination.

However, when I am sorting under a suburb, the url for the route is not being set to localhost:3000/suburb/x (x being page number), and instead, is just being set to suburb/x for the next and previous buttons on the suburbs pagination.

How can I ensure this pagination works under a suburb?

I am aware this may be to do with my routes not being setup properly... Below is pug code for my Bootstrap Pagination and my App.JS code.

JADE (PUG) - index.pug

    nav(aria-label='Page navigation example')#pagination
        ul.pagination
            if currentPage == 1
                li.page-item.disabled
                    a.page-link(href='/' tabindex='-1') Previous

            else
                li.page-item
                    if suburb == null
                        a.page-link(href='/' + (currentPage - 1) tabindex='-1') Previous
                    else
                        a.page-link(href='/' + suburb + '/' + (currentPage - 1) tabindex='-1') Previous
            li.page-item.disabled
                a.page-link(href='#')
                    =currentPage
                    |  of 
                    =totalPages
            if currentPage == totalPages
                li.page-item.disabled
                    a.page-link(href= '/') Next
            else
                li.page-item
                    if suburb == null
                        -var count= currentPage
                        -count++
                        a.page-link(href= '/'  + count) Next
                    else
                        -var count= currentPage
                        -count++
                        a.page-link(href= '/' + suburb + '/' + count ) Next

(JAVASCRIPT)

const express = require('express');
const mysql = require('mysql');
const multer = require('multer');
const path = require('path');
const app = express();

const conn = mysql.createConnection({
    host: "127.0.0.1",
    user: "root",
    password: "",
    database: "realestate"
});

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "./public/uploads");
    },
    filename: function(req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});

const upload = multer({
    storage: storage,
    limits: { filesize: 1000000 },
    fileFilter: function(req, file, cb) {
        checkFiletype(file, cb);
    }
}).single("myImage");

function checkFiletype(file, cb) {
    const filetypes = /jpeg|jpg|png|gif/;
    const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = filetypes.test(file.mimetype);
    if (mimetype && extname) {
        return cb(null, true);
    } else {
        cb('Error: Image Only!');
    }
}

app.use(express.static("public"));

app.set("view engine", "pug");
app.set("views", "./views");

app.get("/about", function(req, res){
    res.render('about', {
        title: 'About Us'
    })
});

app.get("/:suburb?/:page?", (req, res)=>{

    let suburb = req.params.suburb;
    let page = req.params.page || 1;
    let limit = 12;
    let offset;
    console.log(suburb);
    console.log(page);
    if (page == 1) {
        offset = 1;
    } else {
        offset = (page - 1) * limit + 1;
    }

    let sqlSuburbs = "SELECT DISTINCT suburb FROM properties ORDER BY suburb";
    let sqlProperties = "SELECT * FROM WHERE suburb = ?";
    let sqlCountPlaceholder = [suburb];
    let sqlCount = "SELECT COUNT(*) AS 'count' FROM properties WHERE suburb = ?";
    let placeholders = [suburb, limit, offset];

    if (suburb == parseInt(suburb)) {
        page = suburb;
        suburb = "";
        offset = (page - 1) * limit + 1;
        sqlProperties = "SELECT * FROM properties";
        placeholders = [limit, offset];
        sqlCount = "SELECT COUNT(*) AS 'count' FROM properties ORDER BY ?";
        sqlCountPlaceholder = [suburb];
    }

    else if (suburb === undefined) {
        sqlProperties = "SELECT * FROM properties";
        sqlCount = "SELECT COUNT(*) AS 'count' FROM properties ORDER BY ?";
        placeholders = [limit, offset];
        sqlCountPlaceholder = ['suburb'];
        suburb = "";
    }
    else
    {
        sqlProperties = "SELECT * FROM properties where suburb = '" + suburb + "'";
        sqlCount = "SELECT COUNT(*) AS 'count' FROM properties where suburb = '" + suburb + "' ORDER BY ?";
        placeholders = [limit, offset];
        sqlCountPlaceholder = [suburb];
    }
    console.log(placeholders);
    console.log(sqlProperties);
    // get the distinct suburbs
    conn.query(sqlSuburbs, (err, suburb_result) => {
        if (err) throw err
        // Get the properties
        conn.query(sqlProperties + " LIMIT ? OFFSET ?", placeholders, (err, properties_result)=>{
            if (err) throw err
            // Get the query record count
            conn.query(sqlCount, sqlCountPlaceholder, (err, record_count)=>{
                var totalPages = Math.ceil(record_count[0].count / limit);
                if (err) throw err

                if(suburb)
                {
                    suburb = '/' + suburb;
                }
                //Display the page and provide it with values
                res.render("index", {
                    title: 'Home Page',
                    suburbs: suburb_result,
                    properties: properties_result,
                    currentPage: page,
                    next: Number(page)+1 > totalPages?totalPages:Number(page)+1,
                    prev: Number(page)-1 >= 1?Number(page)-1:1,
                    totalPages: totalPages,
                    suburb: suburb
                });
            });
        });
    });
});


app.get("/admin/user/dashboard", (req, res)=>{
    res.render('admin/dashboard', {
        title: 'Dashboard'
    });
});

app.get("/admin/user/fileupload", (req, res)=>{
    res.render("admin/uploads", {
        title: 'File Upload Area'
    });
});



app.post("/admin/user/uploads", (req, res)=>{
    upload(req, res, (err)=> {
        if (err) {
            res.render("admin/uploads", {
                msg: err
            });
        } else {
            if (req.file == undefined) {
                res.render("admin/uploads", {
                    title: "File Upload Area",
                    msg: "Error: No File Selected!"
                })
            } else {
                res.render("admin/uploads", {
                    title: "File Upload Area",
                    msg: "File Uploaded!",
                    file: 'uploads/${req.file.filename}'
                });
            }
        }
    });
});

app.listen(3000, ()=>{

    console.log("Running on port 3000...")
});

Aucun commentaire:

Enregistrer un commentaire