Next.js template
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

data.js 1.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { connectToDatabase } from '../../utils/helpers/dbHelpers';
  2. async function handler(req, res) {
  3. if (req.method !== 'GET') {
  4. return;
  5. }
  6. const pageIndex = req.query.page;
  7. if (pageIndex < 1) {
  8. res.status(422).json({
  9. message: 'Page does not exist ',
  10. });
  11. return;
  12. }
  13. const client = await connectToDatabase();
  14. const db = client.db();
  15. const dataCount = await db.collection('randomData').countDocuments();
  16. if ((pageIndex - 1) * 4 >= dataCount) {
  17. res.status(422).json({
  18. message: 'Page does not exist ',
  19. });
  20. client.close();
  21. return;
  22. }
  23. const dataFromDB = await db
  24. .collection('randomData')
  25. .find()
  26. .skip((pageIndex - 1) * 4)
  27. .limit(4)
  28. .toArray();
  29. if (!dataFromDB) {
  30. res.status(422).json({ message: 'No data!' });
  31. client.close();
  32. return;
  33. }
  34. res.status(201).json({
  35. message: 'Created user!',
  36. data: dataFromDB,
  37. dataCount: dataCount,
  38. });
  39. setTimeout(() => {
  40. client.close();
  41. }, 1500);
  42. }
  43. export default handler;