Skip to content

Type mismatch for non string path and query params? #769

@jpjpjp

Description

@jpjpjp

Hi, I upgraded to 5.11 recently, and I really like the new OperationHandler type templates. However, now that I'm getting better type validation on my handlers, I'm running into an issue with endpoints that have boolean query parameters.

As an example, here is the openapi typegen generated types for an endpoint with a boolean query param:

 namespace GetAllCategories {
        namespace Parameters {
            export type Format = "nested" | "flattened";
            export type IsGroup = false | true;
        }
        export interface QueryParameters {
            format?: Parameters.Format;
            is_group?: Parameters.IsGroup;
        }
        namespace Responses {
            export interface $200 {
                categories?: Components.Schemas.CategoryObject[];
            }
            export type $400 = Components.Schemas.ErrorResponseObject;
            export type $401 = Components.Responses.UnauthorizedToken;
            export type $429 = Components.Responses.RateLimited;
            export type $500 = Components.Responses.ServerError;
        }
    }

And here is the signature for the handler that I've registered:

const getAllCategories: OperationHandler<'getAllCategories'> = async function (
  c: OperationContext<'getAllCategories'>,
  _req: Request,
  res: Response,
): Promise<OperationHandlerResponse<'getAllCategories'>> {

The problem I'm running into is that the type of c.request.query.is_group is actually a string. Below is some debugger output:

c.request.query
{is_group: 'true'}

That has always been the case with opeanpi-backend, and historically, I just set a local boolean with something like:

const is_group = c.request.query?.is_group?.toLowerCase() === 'true'

Given that I've defined c as type OperationContext<'getAllCategories'>, now typescript thinks that this value already IS a boolean, so this type of conversion no longer works. I've found myself having to coerce it as follows:

     const isGroupQuery = c.request?.query?.is_group as unknown as String
      if (isGroupQuery && isGroupQuery.toLowerCase() === 'true') {
        // Handle is_group==true
      } else if (isGroupQuery && isGroupQuery.toLowerCase() === 'false') {
        // Handle is_group==false
      } else {
        // Handle is_group not set
      }

Is it possible to ask openapi-backend to set the values in c.request.query and c.request.params to the defined types?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions