cloudflare / chanfana

OpenAPI 3 and 3.1 schema generator and validator for Hono, itty-router and more!
https://chanfana.pages.dev
MIT License
263 stars 35 forks source link

Allow response headers specification #124

Closed pvarsh closed 4 months ago

pvarsh commented 4 months ago

OpenAPI spec allows the response object to specify headers https://spec.openapis.org/oas/v3.1.0#response-object

{
  "description": "A simple string response",
  "content": {
    "text/plain": {
      "schema": {
        "type": "string",
        "example": "whoa!"
      }
    }
  },
  "headers": {
    "X-Rate-Limit-Limit": {
      "description": "The number of allowed requests in the current period",
      "schema": {
        "type": "integer"
      }
    },
    "X-Rate-Limit-Remaining": {
      "description": "The number of remaining requests in the current period",
      "schema": {
        "type": "integer"
      }
    },
    "X-Rate-Limit-Reset": {
      "description": "The number of seconds left in the current period",
      "schema": {
        "type": "integer"
      }
    }
  }
}

I see that I can specify request headers with itty-router-openapi, but not the response headers. With the following definition, I can find "x-foo" request header in generated openapi.json, but not "x-bar" response header.

export class GetResult extends OpenAPIRoute {
  static schema = {
    tags: ['Results'],
    summary: 'Get operation result',
    headers: {
      "x-foo": new Str({ example: "foo-example" }),
    },
    parameters: {
      ...JSONAcceptHeader,
      id: Path(Str, {
        description: 'Result ID',
        example: '61c9e3c4-9cb2-4fb9-95a5-b48b3772741d',
      }),
    },
    responses: {
      '200': {
        contentType: 'audio/mpeg',
        schema: new Str({ format: 'binary' }),
        headers: {
          "x-bar": new Str({ example: "bar-example" }),
        },
    ...

I'm seeing the response type RouteResponse doesn't have a headers field

export declare type RouteResponse = Omit<ResponseConfig, 'content'> & {
  schema?: Record<any, any>
  contentType?: string
}

Is this something one can do in itty-router-openapi? If not, is that something that can be added?

G4brym commented 4 months ago

Hey @pvarsh i've just published a new version (1.0.13) that adds support for this, read the docs here