Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Required body with optional properties #545

Closed
2 tasks done
hpohlmeyer opened this issue Feb 10, 2022 · 2 comments
Closed
2 tasks done

Required body with optional properties #545

hpohlmeyer opened this issue Feb 10, 2022 · 2 comments
Labels

Comments

@hpohlmeyer
Copy link

hpohlmeyer commented Feb 10, 2022

Prerequisites

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

🚀 Feature Proposal

I would like to have a way to mark a request bodies as required, even if the body only has optional properties.

Motivation

This is a follow-up to #541. While this solves part of my problem, it still does not reflect the defined schema.
The following example illustrates the problem (it uses typebox for schema generation):

// user.types.ts

export const updateUserBody = Type.Object({
  firstName: Type.Optional(Type.String()),
  lastName: Type.Optional(Type.String()),
})

export type UpdateUserRoute = {
  Body: Static<typeof updateUserBody>;
};
// user.routes.ts

export default (fastify) => {
  fastify.put<UpdateUserRoute>(
    "/user",
    { schema: { body: updateUserBody } },
    (request) => console.log(request.body.firstName)
  )
}

Because no property inside the body is required, fastify-swagger will not mark the request body as required.
In theory this would allow me to send a fetch request with an empty body:

const response = await fetch("http://localhost:300/user", {
  method: "put",
  headers: { "Content-Type": "application/json" },
};

console.log(await response.json()) // => [400] Body cannot be empty when content-type is set to 'application/json'

… but fastify always prevents this, because it is not valid JSON. You could argue, that this is not a problem, because you would never do something like this, but if you generate your frontend client with something like oazapfts, you will end up with a signature that has an optional body. And not sending a body will always result in a failed request.

Example

See above

@mcollina
Copy link
Member

What is preventing you to mark the body as required?

@stale
Copy link

stale bot commented Apr 16, 2022

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.

@stale stale bot added the stale label Apr 16, 2022
@stale stale bot closed this as completed Apr 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants