Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
3.9 kB
2
Indexable
Never
"use server";

import { validate } from "validate.js";

const validationRules = {
  name: {
    presence: {
      message: "Nombre inválido",
      allowEmpty: false,
    },
    length: {
      minimum: 3,
      message: "El nombre debe tener al menos 3 caracteres",
    },
  },
  email: {
    presence: {
      message: "Correo inválido",
      allowEmpty: false,
    },
    email: {
      message: "Correo inválido",
    },
  },
  password: {
    presence: {
      message: "Contraseña inválida",
      allowEmpty: false,
    },
    length: {
      minimum: 8,
      message: "La contraseña debe tener al menos 8 carácteres",
    },
  },
  dni: {
    presence: {
      message: "DNI inválido",
      allowEmpty: false,
    },
  },
  schoolId: {
    presence: {
      message: "ID de escuela inválida",
      allowEmpty: false,
    },
  },
  year: {
    presence: {
      message: "Año inválido",
      allowEmpty: false,
    },
  },
  division: {
    presence: {
      message: "Año inválido",
      allowEmpty: false,
    },
  },
  role: {
    presence: {
      message: "Rol inválido",
      allowEmpty: false,
    },
  },
};

type ErrorResponse = {
  errorMessage: string;
};

type SuccessResponseData = {
  name: string;
  email: string;
};

export async function POST(request: Request) {
  const handleSuccessResponse = (data: SuccessResponseData) => {
    return new Response(
      JSON.stringify({
        name,
        email,
      }),
      { status: 201, headers: { "Content-Type": "application/json" } }
    );
  };

  const handleErrorResponse = (error: ErrorResponse) => {
    return new Response(error.errorMessage, {
      status: 500,
      headers: { "Content-Type": "application/json" },
    });
  };

  const sanitizeContent = (content: any) => {
    return content.replace(/<script.*?>.*?<\/script>/gi, "");
  };

  const { name, email, password, dni, schoolId, year, division, role } =
    await request.json();

    console.log(schoolId, year, division, role)

  const dataToValidate = { name, email, password, dni, schoolId, year, division, role };

  const validationErrors = validate(dataToValidate, validationRules, {
    fullMessages: false,
  });

  if (validationErrors) {
    const modifiedErrors: Array<string> = [];

    Object.keys(validationErrors).forEach((field) => {
      const errorMessages: any = validationErrors[field].map((error: any) => {
        return error;
      });

      modifiedErrors.push(errorMessages);
    });

    let errorMessage = modifiedErrors[0][0];

    return handleErrorResponse({
      errorMessage,
    });
  }

  try {
    const api_request = await fetch(
      (process.env.API_URL as string) + "/users/signup",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Strict-Transport-Security":
            "max-age=63072000; includeSubDomains; preload",
        },
        body: JSON.stringify({
          name: sanitizeContent(name),
          email: sanitizeContent(email),
          password: sanitizeContent(password),
          dni: sanitizeContent(dni),
          schoolId: sanitizeContent(schoolId),
          year: sanitizeContent(year),
          division: sanitizeContent(division),
          role: sanitizeContent(role),
        }),
      }
    );

    if (!api_request.ok) {
      const errorObject: ErrorResponse = {
        errorMessage: api_request.statusText
      }
      return handleErrorResponse(errorObject)
    }

    const data = await api_request.json();
    
    if(data.error) {
      const errorObject: ErrorResponse = {
        errorMessage: data.error
      }
      return handleErrorResponse(errorObject);
    }
    return handleSuccessResponse(data);

  } catch (error: any) {
    return handleErrorResponse(error.message || "Error desconocido");
  }
}
Leave a Comment