how to get a nested object from the request query in a get request #3504
ALFmachine
started this conversation in
General
Replies: 1 comment 1 reply
-
You can use hono/validator to handle the validation process yourself. The query is expected to be 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",
// } If you want to use z.validator, you can use z.preprocess." |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
greetings all! loving hono and grateful for this awesome api.
question
asked here on S.O
how can i get a nested key pair object from a url's query string parameters?
for example i would like to extract the following from a url's query params:
i DO have the ability to target specific objects with keys (shown directly below) but i want to be able to pull dynamic key pairs
example
api handler
request
Beta Was this translation helpful? Give feedback.
All reactions