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

[question] How do we get string or string array from GET queries? #180

Closed
tgfjt opened this issue Sep 26, 2023 · 2 comments
Closed

[question] How do we get string or string array from GET queries? #180

tgfjt opened this issue Sep 26, 2023 · 2 comments

Comments

@tgfjt
Copy link

tgfjt commented Sep 26, 2023

I expect the to be valid as an Array even if it has only one element like keys=foo.
Actually, I got an error: path":["keys"],"message":"Expected array, received string"}].

  1. valid: /test?keys=foo&keys=bar
  2. invalid: /test?keys=foo

How do I pass both of 1 & 2?
Thank you.

import { createRoute, z, OpenAPIHono } from '@hono/zod-openapi';

const app = new OpenAPIHono();

const ParamsSchema = z.object({
  keys: z
    .string()
    .array()
    .openapi({
      example: ['foo', 'bar'],
    }),
});

const route = createRoute({
  method: 'get',
  path: '/test',
  request: {
    query: ParamsSchema,
  },
  responses: {
    200: {
      content: {
        'application/json': {
          schema: ParamsSchema,
        },
      },
    },
  },
});
@yusukebe
Copy link
Member

Hi @tgfjt

Try this:

const ParamsSchema = z.object({
  keys: z.union([
    z
      .string()
      .array()
      .openapi({
        example: ['foo', 'bar']
      }),
    z.string().openapi({
      example: 'foo'
    })
  ])
})

const testRoute = createRoute({
  method: 'get',
  path: '/test',
  request: {
    query: ParamsSchema
  },
  responses: {
    200: {
      content: {
        'application/json': {
          schema: ParamsSchema
        }
      },
      description: 'foo'
    }
  }
})

app.openapi(testRoute, (c) => {
  const { keys } = c.req.valid('query') ?? []
  return c.jsonT({
    keys
  })
})

@tgfjt
Copy link
Author

tgfjt commented Sep 27, 2023

@yusukebe
Understood, thank you so much!

Actually, I've tried not to use z.union as I heard that anyOf is not supported by OpenAPITools/openapi-generator.
That's can't be helped. I will try z.union. 👍
OpenAPITools/openapi-generator#10514

@tgfjt tgfjt closed this as completed Sep 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants