arb / celebrate

A joi validation middleware for Express.
MIT License
1.33k stars 66 forks source link

Validating a form data json object? #229

Closed Nikola-Milovic closed 2 years ago

Nikola-Milovic commented 2 years ago

Hello everyone, trying to wrap my head around how to approach this. On my client I send a file and some data alongside that, using FormData, the other data is an object with JSON.stringify around it. This doesn't seem to be picked up by the Joi validator as it expects it to be a string and not an object.

In my client

const SendToServer = async (data: any) => {
    const formData = new FormData();

    const { file, ...otherData } = data;
    if (file) {
        formData.append("file", file);
    }
    formData.append(
        "data",
        new Blob(
            [
                JSON.stringify({
                    otherData,
                }),
            ],
            {
                type: "application/json",
            },
        ),
    );

    const { data: response } = await axios.post(
        `${process.env.SERVER_URL}/api/`,
        formData,
    );
    return response.data;
};

And my server

  route.post(
    "/",
    upload.single("file"),
    celebrate({
      [Segments.BODY]: Joi.object().keys({
        data: Joi.object().keys({
          name: Joi.string().required(),
          otherInformation: Joi.string().required(),
        }),
        file: Joi.any(), // Also I have to add this for some reason
      }),
    }),
    async (req: Request, res: Response, next: NextFunction) => {
      const logger: Logger = Container.get("logger");
      try {
        const data = JSON.parse(req.body.data)
        console.log(req.body.campaignData);
        console.log(data);
        console.log(req.file);

There are hacky ways around this, but interested in genuine solutions

arb commented 2 years ago

What is the problem you are seeing? What is happening or not happening that you expect?

Nikola-Milovic commented 2 years ago

@arb Not really a problem just a question, if I append to form data a JSON string, it's not being parsed as a JSON object but rather as a string. So I was wondering if the type we put in the FormData does it matter or not? As in the above case type: "application/json" was considered a string either way. But after looking into it a bit more I think it's more so Multers thing as it's parsing the body first and then passing it onto the celebrate middleware.

stale[bot] commented 2 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.