fastify-multipart icon indicating copy to clipboard operation
fastify-multipart copied to clipboard

example with fastify-type-provider-zod

Open siddarth opened this issue 1 year ago • 6 comments

Prerequisites

  • [X] I have written a descriptive issue title
  • [X] I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Thank you for all of the work you're putting into this project: it's been a pleasure to use.

It would be great if you could add an example of using multipart form-uploads with the the fastify-type-provider-zod to the README. Between fastify/swagger, fastify-type-provider-zod and fastify/multipart, I'm at a bit of a loss on what the Correct Way to play nicely across these three.

Motivation

No response

Example

No response

siddarth avatar Dec 19 '24 03:12 siddarth

Added, waiting merge #564

Note: In my project I need to verify if the file exists in refine or it throws an error, so is recommended just disable it using hide: true, but if you need it, this could be helpful


z.custom<MultipartFile>()
  .refine(
    (file) => // Don't verify in refine if the file exists throws an error in Swagger UI
      !file || (!!file && file.file.bytesRead <= 10 * 1024 * 1024),
    {
      message: 'The image must be a maximum of 10MB.',
    },
  )

ViniciusLeviVL avatar Jan 07 '25 20:01 ViniciusLeviVL

Added, waiting merge #564

Note: In my project I need to verify if the file exists in refine or it throws an error, so is recommended just disable it using hide: true, but if you need it, this could be helpful

z.custom() .refine( (file) => // Don't verify in refine if the file exists throws an error in Swagger UI !file || (!!file && file.file.bytesRead <= 10 * 1024 * 1024), { message: 'The image must be a maximum of 10MB.', }, )

Hello, I have a similar issue. How can I make it function properly?

import formbody from "@fastify/formbody";
import multipart from "@fastify/multipart";
import fp from "fastify-plugin";

export default fp(async (instance) => {
	await Promise.all([
		instance.register(formbody),
		instance.register(multipart, {
			attachFieldsToBody: "keyValues",
		}),
	]);
});


	fastify.post(
		"/admin/categories",
		{
			schema: {
				body: CreateCategoryRequestSchema,
				consumes: ["multipart/form-data"],
				response: {
					201: SuccessResponseSchema(CreateCategoryResponseSchema),
				},
				tags: ["Admin"],
			},
		},
		async (req, reply) => {
			req.log.info({ body: req.body }, "BODY");

			reply.status(201).send({
				status: "success",
				data: {
					id: 1,
					name: "",
					path: "",
					imageId: null,
					imageUrl: null,
				},
			});
		},
	);
export const CreateCategoryRequestSchema = z.object({
	name: z.string(),
	path: z.string(),
	predefinedPath: z.string().optional(),
	file: z
		.file()
		.max(CategoryImageMaxSize)
		.mime(["image/jpeg", "image/png", "image/webp"]),
});

The examples do not work because the file is converted to a Buffer. What is the correct approach in this case?

Desalutar20 avatar Aug 09 '25 02:08 Desalutar20

Added, waiting merge #564 Note: In my project I need to verify if the file exists in refine or it throws an error, so is recommended just disable it using hide: true, but if you need it, this could be helpful z.custom() .refine( (file) => // Don't verify in refine if the file exists throws an error in Swagger UI !file || (!!file && file.file.bytesRead <= 10 * 1024 * 1024), { message: 'The image must be a maximum of 10MB.', }, )

Hello, I have a similar issue. How can I make it function properly?

import formbody from "@fastify/formbody"; import multipart from "@fastify/multipart"; import fp from "fastify-plugin";

export default fp(async (instance) => { await Promise.all([ instance.register(formbody), instance.register(multipart, { attachFieldsToBody: "keyValues", }), ]); }); fastify.post( "/admin/categories", { schema: { body: CreateCategoryRequestSchema, consumes: ["multipart/form-data"], response: { 201: SuccessResponseSchema(CreateCategoryResponseSchema), }, tags: ["Admin"], }, }, async (req, reply) => { req.log.info({ body: req.body }, "BODY");

  	reply.status(201).send({
  		status: "success",
  		data: {
  			id: 1,
  			name: "",
  			path: "",
  			imageId: null,
  			imageUrl: null,
  		},
  	});
  },

); export const CreateCategoryRequestSchema = z.object({ name: z.string(), path: z.string(), predefinedPath: z.string().optional(), file: z .file() .max(CategoryImageMaxSize) .mime(["image/jpeg", "image/png", "image/webp"]), }); The examples do not work because the file is converted to a Buffer. What is the correct approach in this case?

Set attachFieldsToBody option to true and use z.custom<MultipartFile>() instead z.file().

See the full code example in #564 or fastify-multipart-with-zod-example

ViniciusLeviVL avatar Aug 09 '25 05:08 ViniciusLeviVL

Added, waiting merge #564 Note: In my project I need to verify if the file exists in refine or it throws an error, so is recommended just disable it using hide: true, but if you need it, this could be helpful z.custom() .refine( (file) => // Don't verify in refine if the file exists throws an error in Swagger UI !file || (!!file && file.file.bytesRead <= 10 * 1024 * 1024), { message: 'The image must be a maximum of 10MB.', }, )

Hello, I have a similar issue. How can I make it function properly? import formbody from "@fastify/formbody"; import multipart from "@fastify/multipart"; import fp from "fastify-plugin"; export default fp(async (instance) => { await Promise.all([ instance.register(formbody), instance.register(multipart, { attachFieldsToBody: "keyValues", }), ]); }); fastify.post( "/admin/categories", { schema: { body: CreateCategoryRequestSchema, consumes: ["multipart/form-data"], response: { 201: SuccessResponseSchema(CreateCategoryResponseSchema), }, tags: ["Admin"], }, }, async (req, reply) => { req.log.info({ body: req.body }, "BODY");

  	reply.status(201).send({
  		status: "success",
  		data: {
  			id: 1,
  			name: "",
  			path: "",
  			imageId: null,
  			imageUrl: null,
  		},
  	});
  },

); export const CreateCategoryRequestSchema = z.object({ name: z.string(), path: z.string(), predefinedPath: z.string().optional(), file: z .file() .max(CategoryImageMaxSize) .mime(["image/jpeg", "image/png", "image/webp"]), }); The examples do not work because the file is converted to a Buffer. What is the correct approach in this case?

Set attachFieldsToBody option to true and use z.custom<MultipartFile>() instead z.file().

See the full code example in #564 or fastify-multipart-with-zod-example

What about the other fields? In addition to the file, there will be other fields as well.

Desalutar20 avatar Aug 09 '25 07:08 Desalutar20

In this case, you can use preprocessing like this:

z.object({
  image: z.custom<MultipartFile>(),
  anotherField: z.preprocess(
    (file) => (file as MultipartValue).value,
    z.string() /* validation here */,
  ),
  /* another fields here */
}),

You can use attachFieldsToBody: "keyValues" to avoid preprocessing, but in that case, you will receive a Buffer for files that are not text/plain I will update the examples above.

ViniciusLeviVL avatar Aug 09 '25 12:08 ViniciusLeviVL

In this case, you can use preprocessing like this:

z.object({ image: z.custom(), anotherField: z.preprocess( (file) => (file as MultipartValue).value, z.string() /* validation here /, ), / another fields here */ }),

You can use attachFieldsToBody: "keyValues" to avoid preprocessing, but in that case, you will receive a Buffer for files that are not text/plain I will update the examples above.

Thank you, but I solved the problem this way, and according to your example, the image field in Swagger will be any.

import z from "zod";
import { CategoryImageMaxSize } from "../../const/zod.js";
import { CategorySchema } from "./category.schema.js";

export const CreateCategoryRequestSchema = z.object({
	name: z.string().nonempty(),
	path: z
		.string()
		.nonempty()
		.regex(/^[a-z]+$/i, "The field can only contain Latin letters."),
	predefinedPath: z
		.string()
		.nonempty()
		.regex(
			/^[a-z]+(\.[a-z]+)?$/i,
			"Must be either a single word or two parts separated by a dot, only Latin letters.",
		)
		.optional(),
	image: z
		.file()
		.max(CategoryImageMaxSize)
		.mime(["image/jpeg", "image/png", "image/webp"]),
});

export const CreateCategoryResponseSchema = CategorySchema;

export type CreateCategoryRequest = z.Infer<typeof CreateCategoryRequestSchema>;

	fastify.post(
		"/admin/categories",
		{
			preHandler: multipartOnly,
			preValidation: async (req) => {
				const formData = await req.formData();
				//@ts-expect-error ...
				req.body = Object.fromEntries(formData.entries());
			},
			schema: {
				body: CreateCategoryRequestSchema,
				consumes: ["multipart/form-data"],
				response: {
					201: SuccessResponseSchema(CreateCategoryResponseSchema),
					400: z.union([ErrorResponseSchema, ValidationErrorResponseSchema]),
				},
				tags: ["Admin"],
			},
		},
		async (req, reply) => {
			const category = await categoryService.createCategory(req.body, req.log);

			reply.status(201).send({
				status: "success",
				data: category,
			});
		},
	);

Desalutar20 avatar Aug 10 '25 10:08 Desalutar20