79392337

Date: 2025-01-27 22:41:03
Score: 0.5
Natty:
Report link

i received a responsehttps://github.com/orgs/honojs/discussions/3504#discussioncomment-10926286 from maou-shonen here which solved this issue.

import { Hono } from "hono"
import { validator } from "hono/validator"
import { z } from "zod"

// This function was generated by ChatGPT. Please modify it as needed.
function parseQuery(query: Record<string, string | string[]>) {
  const result = {}

  for (const [key, value] of Object.entries(query)) {
    const keys = key.split(/[\[\]]+/).filter(Boolean)
    let current = result

    keys.forEach((nestedKey, index) => {
      if (index === keys.length - 1) {
        current[nestedKey] = Array.isArray(value) ? value[0] : value
      } else {
        current[nestedKey] = current[nestedKey] || {}
        current = current[nestedKey]
      }
    })
  }

  return result
}

const app = new Hono().get(
  "/",
  validator("query", (value) => {
    const schema = z.object({
      cursor: z.object({
        pk: z.string().optional(),
        sk: z.string().optional(),
      }),
      limit: z.string().optional(),
    })

    return schema.parse(parseQuery(value))
  }),
  async (c) => {
    const q = c.req.valid("query")
    return c.json(q)
  },
)

const cursor =
  "cursor[pk]=PAGE&cursor[sk]=PAGE#1728586654826-c2c67760-d28c-4abe-99f8-2286da2fc5b5"
const response = await app.request(`http://localhost:3000/?${cursor}&limit=1`)
const data = await response.json()

// data =
// {
//   cursor: {
//     pk: "PAGE",
//     sk: "PAGE#1728586654826-c2c67760-d28c-4abe-99f8-2286da2fc5b5",
//   },
//   limit: "1",
// }
Reasons:
  • Probably link only (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: ALFmachine