WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content

[zod-openapi] validate nested query #1587

@prpanto

Description

@prpanto

What is the feature you are proposing?

I have a nested query like ?filter[color]=red&filter[size]=large&user[post][id]=385&sort=-createdAt&include=author,comments&active=true and I want to validate. In zod-validator I use qs lib to make the query like an object and after that i parse with zod. In zod-openapi I love to get query to make the same. See my example above.

const route = createRoute({
  ...
  request: {
    query: (query) => {
      // query example: "?filter[color]=red&filter[size]=large&user[post][id]=385&sort=-createdAt&include=author,comments&active=true"
      
      const queryObject = qs.parse(query, {
        ignoreQueryPrefix: true,
        decoder: (str: string, defaultDecoder: qs.defaultDecoder, charset: string, type: "key" | "value") => {    
          if (type === "value" && !!Number(str)) {
            return Number(str);
          }

          if (type === "value" && str === "true") {
            return true;
          }
          
          if (type === "value" && str === "false") {
            return false;
          }

          if (type === "value" && str.includes(",")) {
            return str.split(",").map((s: string) => s.trim());
          }

          return defaultDecoder(str);
        }
      });

      const schema = z.object({
        filter: z.object({
          color: z.string().optional(),
          size: z.string().optional(),
        }).optional(),
        user: z.object({
          post: z.object({
            id: z.int().optional(),
          }).optional(),
        }).optional(),
        sort: z.string().optional(),
        include: z.array(z.string()).optional(),
        active: z.boolean().optional(),
      });

      return schema.parse(queryObject);
    },
  },
  ...
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions