| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- const Person = require('../../../models/person');
- import { NextApiRequest, NextApiResponse } from 'next';
- import dbConnect from '../../../utils/helpers/dbHelpers';
- import {
- IPerson,
- PersonIdsResponse,
- } from '../../../utils/interface/personInterface';
-
- async function handler(
- req: NextApiRequest,
- res: NextApiResponse<PersonIdsResponse>
- ) {
- const { method } = req;
-
- await dbConnect();
-
- switch (method) {
- case 'GET': {
- try {
- const dataCount: number = await Person.countDocuments();
-
- if (dataCount === 0) {
- res.status(200).json({
- message: 'No data.',
- dataIds: [],
- });
- break;
- }
-
- const dataFromDB: Array<IPerson> = await Person.find({}).limit(4);
-
- if (!dataFromDB) {
- throw new Error('No data!');
- }
-
- const dataIds = dataFromDB.map((item) => item.customID);
-
- res.status(200).json({
- message: 'Fetch ids successfull!',
- dataIds: dataIds,
- });
- } catch (error) {
- if (error instanceof Error)
- res.status(400).json({ message: error.message });
- else res.status(400).json({ message: 'Unexpected error' + error });
- }
- break;
- }
- default:
- res.status(405).json({ message: 'Method not allowed' });
- break;
- }
- }
-
- export default handler;
|