Skip to content

Instantly share code, notes, and snippets.

@asrorbekh
Created July 17, 2024 12:59
Show Gist options
  • Save asrorbekh/3f9a1f6a441aec8c6271cc4da1ec975a to your computer and use it in GitHub Desktop.
Save asrorbekh/3f9a1f6a441aec8c6271cc4da1ec975a to your computer and use it in GitHub Desktop.
const express = require('express');
const { MongoClient } = require('mongodb');
// Initialize Express app
const app = express();
const port = 3000;
// MongoDB Connection URL and Database Name
const url = 'mongodb://localhost:27017';
const dbName = 'app_db';
const collectionName = 'packages';
app.use(express.json());
async function connectDB() {
const client = new MongoClient(url);
await client.connect();
return client.db(dbName).collection(collectionName);
}
app.get('/api/data', async (req, res) => {
let limit = parseInt(req.query.limit) || 10;
limit = Math.min(limit, 20);
const page = parseInt(req.query.page) || 1;
const skip = (page - 1) * limit;
const query = {};
// Handle the 'query' parameter for wildcard searches
if (req.query.query) {
const searchValue = req.query.query;
query.reason = { $regex: searchValue.replace(/%/g, '.*'), $options: 'i' };
}
const collection = await connectDB();
try {
const cursor = collection.find(query).skip(skip).limit(limit);
const results = await cursor.toArray();
// Calculate pagination info
const totalDocuments = await collection.countDocuments(query);
const totalPages = Math.ceil(totalDocuments / limit);
// Calculate prevPage and nextPage
const prevPage = page > 1 ? page - 1 : null;
const nextPage = page < totalPages ? page + 1 : null;
// Response object structure
const responseObject = {
code: 200,
status: 'success',
data: results,
pagination: {
total: totalDocuments,
totalPages: totalPages,
currentPage: page,
perPage: limit,
prevPage: prevPage,
nextPage: nextPage
}
};
res.json(responseObject);
} catch (err) {
console.error('Error fetching data:', err);
res.status(500).json({ code: 500, status: 'error', message: 'Internal server error' });
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment