| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- const Person = require('../../models/person');
- import dbConnect from '../../utils/helpers/dbHelpers';
-
- async function handler(req, res) {
- const { method } = req;
-
- await dbConnect();
-
- const pageIndex = req.query.page;
-
- if (pageIndex < 1) {
- res.status(422).json({
- message: 'Page does not exist ',
- });
- return;
- }
-
- switch (method) {
- case 'GET': {
- try {
- const dataCount = await Person.countDocuments();
-
- if (dataCount === 0) {
- res.status(200).json({
- message: 'No data.',
- data: [],
- dataCount: 0,
- });
- break;
- }
-
- if ((pageIndex - 1) * 4 >= dataCount) {
- throw new Error('Page does not exist!');
- }
-
- const dataFromDB = await Person.find({})
- .skip((pageIndex - 1) * 4)
- .limit(4);
-
- if (!dataFromDB) {
- throw new Error('No data!');
- }
-
- res.status(200).json({
- message: 'Fetched data succesfully',
- data: dataFromDB,
- dataCount,
- });
- } catch (error) {
- res.status(400).json({ message: error.message });
- }
- break;
- }
- case 'POST': {
- try {
- const person = await Person.create(
- req.body
- ); /* create a new model in the database */
- res.status(201).json({ message: 'Created succesfully!', data: person });
- } catch (error) {
- res.status(400).json({ success: false });
- }
- break;
- }
- default:
- res.status(405).json({ message: 'Method not allowed' });
- break;
- }
- }
-
- export default handler;
|