Snai3i-LandingPage-FormBuilder / backend / src / controllers / formController.ts
formController.ts
Raw
import { type NextFunction, type Request, type Response } from 'express';
import Form from '../models/formModel';
import { RequestWithUser } from '../types/Express';
import { ErrorResponse, SuccessResponse } from '../utils/response';
import { HttpCodes } from '../config/errors';
import Logger from '../utils/logger';


export const getAllForms = async (
  req: RequestWithUser,
  res: Response,
  next: NextFunction
) => {
  try {
    const page = Number(req.query.page) || 0;
    const pageSize = Number(req.query.pageSize) || 10;
    const skip = page * pageSize;
    const searchQuery = req.query.search;

    Logger.info(`Fetching forms page ${page} with page size ${pageSize}.`);

    const query =
      searchQuery === undefined || searchQuery === ''
        ? { name: { $regex: searchQuery, $options: 'i' } }
        : {};

    const total = await Form.countDocuments(query);

    if (req.query.page && req.query.page !== '0' && skip >= total) {
      Logger.error(`Failed to get forms page ${page} doesn't exist.`);
      return ErrorResponse(
        res,
        HttpCodes.BadRequest.code,
        `Failed to get forms page ${page} doesn't exist.`
      );
    }

    const forms = await Form.find(query)
      .sort(req.query.sort?.toString() ?? '')
      .skip(skip)
      .limit(pageSize);

    return SuccessResponse(
      res,
      HttpCodes.Accepted.code,
      { forms, total },
      'Forms fetched successfully.'
    );
  } catch (error) {
    Logger.error(`Error occurred while fetching forms : ${error}`);
    return ErrorResponse(
      res,
      HttpCodes.InternalServerError.code,
      'Failed to fetch forms. Please try again!'
    );
  }
};

export const deleteForms = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  try {
    const { forms } = req.body;

    await Form.deleteMany({ _id: { $in: forms } });

    Logger.info(`Forms ${forms} deleted successfully.`);
    SuccessResponse(
      res,
      HttpCodes.Accepted.code,
      null,
      'Forms deleted successfully.'
    );
  } catch (error) {
    Logger.error(`Failed to delete forms - ${error}`);
    return ErrorResponse(
      res,
      HttpCodes.InternalServerError.code,
      'Failed to delete forms. Please try again!'
    );
  }
};

export const getForm = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  try {
    const form = await Form.findById(req.params.id);
    if (!form) {
      Logger.error(
        `Failed to get form - No form found with that ID - ${req.params.id}`
      );
      return ErrorResponse(
        res,
        HttpCodes.NotFound.code,
        'No form found with that ID'
      );
    }

    Logger.info(`Form ${form?.name} fetched successfully.`);
    return SuccessResponse(
      res,
      HttpCodes.Accepted.code,
      form,
      'Form fetched successfully.'
    );
  } catch (error) {
    Logger.error(`Failed to get form - ${error}`);
    return ErrorResponse(
      res,
      HttpCodes.InternalServerError.code,
      'Failed to get form. Please try again!'
    );
  }
};

export const createForm = async (
  req: RequestWithUser,
  res: Response,
  next: NextFunction
) => {
  try {
    const { name, elements } = req.body;

    // joi validation
    // if (!name)
    //   return next(new AppError('Please provide the name of the form!', 400));

    if (elements.length === 0) {
      Logger.error(
        `Failed to create form - Please provide at least one element to create a form.`
      );
      return ErrorResponse(
        res,
        HttpCodes.BadRequest.code,
        'Please provide at least one element to create a form.'
      );
    }
    const newForm = await Form.create({
      name,
      elements: elements ?? [],
      user: req.user?._id,
    });

    Logger.info(`Form ${newForm.name} created successfully.`);
    return SuccessResponse(
      res,
      HttpCodes.Created.code,
      { form: newForm },
      'Form created successfully.'
    );
  } catch (error) {
    Logger.error(`Failed to create form - ${error}`);
    return ErrorResponse(
      res,
      HttpCodes.InternalServerError.code,
      'Failed to create form. Please try again!'
    );
  }
};

export const updateForm = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  // joi validation
  const formId = req.params.id;
  const newForm = req.body;

  try {
    const form = await Form.findByIdAndUpdate(formId, newForm, {
      new: true,
    });
    if (!form) {
      Logger.error(`Failed to update form - Form not found.`);
      return ErrorResponse(
        res,
        HttpCodes.NotFound.code,
        'No form found with that ID.'
      );
    }

    Logger.info(`Form ${form.name} updated successfully.`);
    return SuccessResponse(
      res,
      HttpCodes.Accepted.code,
      { form },
      'Form updated successfully.'
    );
  } catch (error) {
    Logger.error(`Failed to update form - ${error}`);
    return ErrorResponse(
      res,
      HttpCodes.InternalServerError.code,
      'Failed to update form. Please try again!'
    );
  }
};

export const deleteForm = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  try {
    const form = await Form.findByIdAndDelete(req.params.id);
    if (!form) {
      Logger.error(`Failed to delete form - Form not found.`);
      return ErrorResponse(
        res,
        HttpCodes.NotFound.code,
        'No form found with that ID.'
      );
    }

    Logger.info(`Form ${form.name} deleted successfully.`);
    return SuccessResponse(
      res,
      HttpCodes.Accepted.code,
      null,
      'Form deleted successfully.'
    );
  } catch (error) {
    Logger.error(`Failed to delete form - ${error}`);
    return ErrorResponse(
      res,
      HttpCodes.InternalServerError.code,
      'Failed to delete form. Please try again!'
    );
  }
};