| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- import { connectToDatabase } from '../../utils/helpers/dbHelpers';
-
- async function handler(req, res) {
- if (req.method !== 'GET') {
- return;
- }
-
- const pageIndex = req.query.page;
-
- if (pageIndex < 1) {
- res.status(422).json({
- message: 'Page does not exist ',
- });
- return;
- }
-
- const client = await connectToDatabase();
- const db = client.db();
-
- const dataCount = await db.collection('randomData').countDocuments();
-
- if ((pageIndex - 1) * 5 >= dataCount) {
- res.status(422).json({
- message: 'Page does not exist ',
- });
- client.close();
- return;
- }
-
- const dataFromDB = await db
- .collection('randomData')
- .find()
- .skip((pageIndex - 1) * 5)
- .limit(5)
- .toArray();
-
- if (!dataFromDB) {
- res.status(422).json({ message: 'No data!' });
- client.close();
- return;
- }
-
- res.status(201).json({
- message: 'Created user!',
- data: dataFromDB,
- dataCount: dataCount,
- });
-
- setTimeout(() => {
- client.close();
- }, 1500);
- }
-
- export default handler;
|