ts-rest / ts-rest

RPC-like client, contract, and server implementation for a pure REST API
https://ts-rest.com
MIT License
2.11k stars 91 forks source link

Support multiple content-type responses #583

Open toteto opened 2 months ago

toteto commented 2 months ago

Is your feature request related to a problem? Please describe.

There are cases where the having more flexible content-type response header value makes sense. Some come from the content type the client requests/supports, other is where the server picks what is best content-type depending on the logic.

Describe the solution you'd like

Initially I think that c.otherResponse should be considered as place to implement this feature in the contract. One option is to have the contentType be an array with all options instead of string, where the body would be union of the schemas. But more appropriate would be I think to have union of the whole response.

Something like this:

responses: {
    200: c.otherResponse([
        { contentType: 'application/json-ld', body: c.type<void>() }, 
        { contentType: 'application/json', body: c.type<void>() }
    ]),
},

On the server side, probably returning content-type under headers would be sufficient?

Describe alternatives you've considered

The current workaround is to have separate response entries and disregard the HTTS status code:

responses: {
    200: c.otherResponse({ contentType: 'application/json-ld', body: c.type<void>() }),
    201: c.otherResponse({ contentType: 'application/json', body: c.type<void>() }),
},