I've created a basic APi for my project using node and express. I wanted to add pagination information to the data such as limit, data size, page etc.
I managed to do this but I've got one bug I can't fix. When I load the api in the browser and press refresh it will show me the next set of objects ( as the limit is 10 ), if I press refresh again the results are empty.
{"collectionSize":29,"numOfPages":3,"results":[]}
Is this normal behaviour?
App.js
import express from 'express'
import cors from 'cors'
import indexRouter from './routes/indexRouter.js'
const app = express()
const port = process.env.PORT || 4041
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(cors()) // <---- use cors middleware
app.use('/', indexRouter)
app.listen(port, () => {
console.log(`server is running on port: ${port}`)
})
Router.js
import express from 'express';
import projectData from "../mocks/data.js";
const router = express.Router();
const projects = projectData;
router.get("/api/projects", paginate(projects), (req, res) => {
const { paginatedResult } = res;
res.json( paginatedResult );
});
const config = {
startingPage: 1,
limitDefault: 10,
modelSize: projects.length,
}
function paginate(model) {
return async (req, res, next) => {
const page = parseInt(req.query.page) || config.startingPage;
const limit = parseInt(req.query.limit) || config.limitDefault;
const startIndex = (page - 1) * limit;
const endIndex = page * limit;
const numOfPages = Math.round(config.modelSize / limit);
const result = {};
if (endIndex < model.length) {
result.next = {
page: page + 1,
limit: limit,
};
}
if (startIndex > 0) {
result.previous = {
page: page - 1,
limit: limit,
};
}
try {
result['collectionSize'] = config.modelSize;
result['numOfPages'] = numOfPages;
result.results = model.splice(startIndex, endIndex);
res.paginatedResult = result;
return next();
} catch (e) {
res.status(500).json({ message: e.message });
}
};
}