Koperumsozhan VR
Koperumsozhan VR

Reputation: 79

Fastify web framework not supporting multiple middleware - NodeJS

I have created one middleware for found the duplicate for all field and all model dynamically based on arguments Now I try to validate 1st field its working find when I try array type in preHandler its throwing error

//customer.route.js

import { addcustomer } from "../controllers/customer.controller.js";
import { CustomerModel } from "../models/customer.model.js";
import { duplicateChecker } from "../middleware/duplicateCheck.middleware.js";

import { addCustomerSchema } from "../validations/customer.validation.js";

const customerRoutes = async (fastify, options) => {
  fastify.post(
    "/add",
    {
      schema: addCustomerSchema,
      preHandler: [ //multiple middleware call
        duplicateChecker({
          model: CustomerModel,
          field: "customer_name",
          propertyName: "customer_name",
        }),
        duplicateChecker({
          model: CustomerModel,
          field: "desctiption",
          propertyName: "desctiption",
        }),
      ],
    },
    addcustomer
  );
};

export { customerRoutes };

//duplicateCheck.middleware.js

import { Op } from "sequelize";

function duplicateChecker(options = []) {
  const {
    model,
    field,
    propertyName,
    action = null,
    updateField = null,
    updatePropertyName = null,
    objectType = "body",
  } = options;

  return async (request, reply, next) => {
    try {
      const value = request[objectType][propertyName];
      const updateValue = request[objectType][updatePropertyName];
      let existingRecord;
      if (action === "update") {
        existingRecord = await model.findOne({
          where: { [field]: value, [updateField]: { [Op.not]: updateValue } },
        });
      } else {
        existingRecord = await model.findOne({ where: { [field]: value } });
      }
      if (existingRecord) {
        return reply
          .code(400)
          .send({ error: `${field} '${value}' already exists` });
      } else {
        next();
      }
    } catch (error) {
      reply.code(500).send({ error: "Internal Server Error" });
    }
  };
}

export { duplicateChecker };

If I call with one time its working fine

fastify.post(
    "/add",
    {
      schema: addCustomerSchema,
      preHandler: duplicateChecker({
          model: CustomerModel,
          field: "customer_name",
          propertyName: "customer_name",
        }),
    },
    addcustomer
  );

when I try to call second time its getting issue

FastifyError {code: 'FST_ERR_HOOK_INVALID_ASYNC_HANDLER', name: 'FastifyError', statusCode: 500, message: "Async function has too many arguments. Async hooks should not use the 'done' argument.", stack: 'FastifyError: Async function has too many arg…ons (node:internal/process/task_queues:82:21)'}

Can anyone help me on this?

Upvotes: 0

Views: 142

Answers (0)

Related Questions