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.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const Person = require('../../models/person');
  2. import dbConnect from '../../utils/helpers/dbHelpers';
  3. async function handler(req, res) {
  4. const { method } = req;
  5. await dbConnect();
  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. switch (method) {
  14. case 'GET': {
  15. try {
  16. const dataCount = await Person.countDocuments();
  17. if (dataCount === 0) {
  18. res.status(200).json({
  19. message: 'No data.',
  20. data: [],
  21. dataCount: 0,
  22. });
  23. break;
  24. }
  25. if ((pageIndex - 1) * 4 >= dataCount) {
  26. throw new Error('Page does not exist!');
  27. }
  28. const dataFromDB = await Person.find({})
  29. .skip((pageIndex - 1) * 4)
  30. .limit(4);
  31. if (!dataFromDB) {
  32. throw new Error('No data!');
  33. }
  34. res.status(200).json({
  35. message: 'Fetched data succesfully',
  36. data: dataFromDB,
  37. dataCount,
  38. });
  39. } catch (error) {
  40. res.status(400).json({ message: error.message });
  41. }
  42. break;
  43. }
  44. case 'POST': {
  45. try {
  46. const person = await Person.create(
  47. req.body
  48. ); /* create a new model in the database */
  49. res.status(201).json({ message: 'Created succesfully!', data: person });
  50. } catch (error) {
  51. res.status(400).json({ success: false });
  52. }
  53. break;
  54. }
  55. default:
  56. res.status(405).json({ message: 'Method not allowed' });
  57. break;
  58. }
  59. }
  60. export default handler;