From 2434108770f61cc73695a4330ac9067486a28e8e Mon Sep 17 00:00:00 2001 From: Ethan Ho Date: Mon, 5 Feb 2024 21:31:03 -0800 Subject: [PATCH] 34 catalog pagination backend (#42) * Modified /catalog get request to accept limit and page parameter for pagination Co-authored-by: Maithy Le * Modified /catalog get to return data and amount of events Co-authored-by: Maithy Le * merge catalog query+filter with pagination --------- Co-authored-by: Maithy Le Co-authored-by: ThatMegamind <92563733+ThatMegamind@users.noreply.github.com> Co-authored-by: michellelin1 --- common/utils.js | 7 ++++++- routes/catalog.js | 26 +++++++++++++++++++------- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/common/utils.js b/common/utils.js index 14fad66..d9f6238 100644 --- a/common/utils.js +++ b/common/utils.js @@ -20,6 +20,11 @@ const isISODate = (str) => { } }; +// dependency for catalog.js +const isInteger = (value) => { + return value && /^\d+$/.test(value); +}; + const isObject = (o) => { return o === Object(o) && !isArray(o) && typeof o !== 'function' && !isISODate(o); }; @@ -52,4 +57,4 @@ const keysToCamel = (data) => { return data; }; -module.exports = { keysToCamel }; +module.exports = { keysToCamel, isInteger }; diff --git a/routes/catalog.js b/routes/catalog.js index 2c5ed3a..71f3840 100644 --- a/routes/catalog.js +++ b/routes/catalog.js @@ -1,15 +1,22 @@ const express = require('express'); - const { db } = require('../server/db'); const catalogRouter = express.Router(); -const { keysToCamel } = require('../common/utils'); -// modify /catalog +const { keysToCamel, isInteger } = require('../common/utils'); + // -- GET - Returns all data from the catalog table catalogRouter.get('/', async (req, res) => { try { const { title, eventType, subject, season, year } = req.query; - let query = 'SELECT * FROM catalog WHERE 1=1'; + + let { limit, page } = req.query; + limit = isInteger(limit) ? parseInt(limit, 10) : 10; + page = isInteger(page) ? parseInt(page, 10) : 1; + + const offset = (page - 1) * limit; + + let query = ' FROM catalog WHERE 1=1'; + const params = []; if (title) { @@ -47,10 +54,15 @@ catalogRouter.get('/', async (req, res) => { params.push(''); } - query += ' ORDER BY title ASC'; + const eventCount = await db.query(`SELECT COUNT(*) ${query};`, params); + + query += ' ORDER BY title ASC LIMIT $6 OFFSET $7;'; + params.push(limit); + params.push(offset); + + const reqInfo = await db.query(`SELECT * ${query}`, params); - const reqInfo = await db.query(query, params); - res.status(200).json(keysToCamel(reqInfo)); + res.status(200).json(keysToCamel({ events: reqInfo, count: eventCount })); } catch (err) { res.status(500).send(err.message); }