Sindbad~EG File Manager

Current Path : /home/infinitibizsol/.trash/controllers.8/contact/
Upload File :
Current File : /home/infinitibizsol/.trash/controllers.8/contact/linkedAccount.js

import db from "../../model/index";
import { successResponse, failedResponse } from "../../utils/responseFormat";
import catchAsync from "../../utils/catchAsync";
import AppError from "../../utils/apiError";

const validateDuplicateEntry = async (query) => {
  let document = await db.LinkedAccount.findOne(query);
  if (document) return true;
  return false;
};

const index = catchAsync(async (req, res, next) => {
  const query = req.query;
  let allData = await db.LinkedAccount.find(query)
    .populate({
      path: "contact_id",
      select: ["_id", "first_name"],
    })
    .exec();
  return successResponse(res, allData);
});

const add = catchAsync(async (req, res, next) => {
  let { contact_id } = req.body;
  const isDuplicate = await validateDuplicateEntry({ contact_id });
  if (isDuplicate) {
    return next(
      new AppError(
        "Duplicate entry is not allowed.you can only update it.",
        404
      )
    );
  }
  const linkedAccount = req.body;
  const result = new db.LinkedAccount(linkedAccount);
  await result.save();
  return successResponse(res, result, "LinkedAccount saved successfully.");
});

const edit = catchAsync(async (req, res, next) => {
  const contact_id = req.params.id;
  let result = await db.LinkedAccount.findOneAndUpdate(
    { contact_id },
    { $set: req.body },
    { new: true }
  );
  if (!result) {
    return next(new AppError("No data found.", 404));
  }
  return successResponse(res, result, "LinkedAccount updated successfully");
});

const deleteData = catchAsync(async (req, res, next) => {
  const contactId = req.params.id;
  // Delete the contact itself
  const deletedcontact = await db.LinkedAccount.findByIdAndDelete({
    _id: contactId,
  });

  if (!deletedcontact) {
    return next(new AppError("No data found.", 404));
  }
  return successResponse(
    res,
    deletedcontact,
    "LinkedAccount and related data deleted successfully."
  );
});

const saveLinkedAccount = catchAsync(async (req, res, next) => {
  const { contact_id, linked_accounts } = req.body;

  let linkedAccount;
  linkedAccount = await db.LinkedAccount.findOne({
    contact_id: contact_id,
  });

  if (linkedAccount) {
    // Update the existing record
    linkedAccount.linked_accounts = linked_accounts;
  } else {
    // Create a new record
    linkedAccount = new db.LinkedAccount(req.body);
  }
  await linkedAccount.save();

  return successResponse(
    res,
    linkedAccount,
    "LinkedAccount saved successfully."
  );
});

export default { index, add, edit, deleteData, saveLinkedAccount };

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists