fastify / help

Need help with Fastify? File an Issue here.
https://www.fastify.io/
64 stars 8 forks source link

Fastify-mulipart schema validation with typebox #481

Open mahendraHegde opened 3 years ago

mahendraHegde commented 3 years ago

💬 Example for typescript + fastify-multipart + typebox schema validation

I'm using fastify-multipart for file upload, and other form data, but i dont see any example how to use the schema validation with typebox

any help would be appreciated

Eomm commented 3 years ago

What did you try so far? Are you having some errors?

I have not used this module

mahendraHegde commented 3 years ago

Thanks for the response @Eomm , At the time of posting the question i had no clue how to proceed, but later I checked the fastify-multipart's internal js implementation for schema validation, I ported the same to typebox, but i couldn't find the right way to handle file stream with typebox

const ImageUploadForm = Type.Object({
  image: Type.Object({
    encoding: Type.String(),
    filename: Type.String(),
    mimetype: Type.Optional(Type.String()),
    file: Type.Any(),  //any better way??
    type: Type.Optional(Type.String()),
  }),
  description: Type.Optional(
    Type.Object({
      value: Type.String(),
    })
  ),
});

export type ImageUploadFormType = Static<typeof ImageUploadForm>;

export const uploadPhotoSchema = {
  body: ImageUploadForm,
  response: {
    204: {},
  },
} as const;

now i can access req.body.image.file buffer.

the above validation is working. I'm looking for a better way to validate req.body.image.file , I'm not sure how to do it with typebox.

climba03003 commented 3 years ago

the above validation is working. I'm looking for a better way to validate req.body.image.file , I'm not sure how to do it with typebox.

I think we should accept that validating multipart with files is not a great idea. As file is not a buffer string, there are no default type for ajv to accept or validate it. You may need a custom validator or keyword.

https://github.com/ajv-validator/ajv/issues/1555 https://github.com/ajv-validator/ajv/issues/1556