how to get a nested object from the request query in a get request #3504
ALFmachine
started this conversation in
General
Replies: 2 comments 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
-
|
I was late to the party but I find a good solution for parsing the query to beautiful object. I use import { z } from "zod";
import qs from "qs";
const query = "?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);
}
});
console.log(queryObject);
const querySchema = 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(),
});
const result = querySchema.parse(queryObject); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
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