ALFmachine
ALFmachine

Reputation: 808

using honojs how to get a nested object from the request query in a get request

question

asked here for the honojs team

how can i get a nested key pair object from a url's query string parameters using honojs?

for example i would like to extract the following from a url's query params:

cursor[pk]=PK_NAME&cursor[sk]=SK_NAME#1728586654826-c2c67760-d28c-4abe-99f8-2286da2fc5b5

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

console.log('QUERY', c.req.query('cursor[pk]'))

example

api handler

app.get(
  '/',
  zValidator(
    'query',
    z.object({
      cursor: z.record(z.string(), z.string()).default({}),
      limit: z.coerce.number().int().positive().default(50),
      order: z.enum(['asc', 'desc']).default('desc'),
    })
  ),
  async (c) => {
    const { cursor, limit, order } = c.req.valid('query')

    console.log('valid cursor', cursor) // undefined
    console.log('QUERY', c.req.query('cursor')) // undefined
    console.log('QUERIES', c.req.queries('cursor')) //undefined

    const data = await queryRecords({ cursor, limit, order })

    return c.json({ cursor: data.cursor, records: data.records })
  }
)

request

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

logs example

Upvotes: 1

Views: 288

Answers (0)

Related Questions