spencerwooo / substats

( `д′) how many followers do i have? how many!
https://substats.swo.moe
MIT License
813 stars 56 forks source link

Getting multiple query params #44

Open yusukebe opened 2 years ago

yusukebe commented 2 years ago

Hi there ✋

It's not sure that you know this way already, but I want to tell you. I know how to get multiple query params with ittry-router. Inside of the handler, we can get Request object. So, we can get multiple query params by getting url strings, passing into URLSearchParams, and using getAll() method. This is code:

import { Router } from 'itty-router'

const router = Router()

router.get('/', (req) => {
  const url = new URL(req.url)
  const search = new URLSearchParams(url.search)
  const params = search.getAll('foo')
  return new Response(JSON.stringify(params), {
    headers: {
      'Content-Type': 'application/json',
    },
  })
})

addEventListener('fetch', (event) => event.respondWith(router.handle(event.request)))

Run with Wrangler or Miniflare, and then access like this:

$ curl 'http://localhost:8787/?foo=hello&foo=morning&foo=night'
["hello","morning","night"]

You can get multi values.

Note:

You can also use Hono instead of ittry-router.

import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => {
  const url = new URL(c.req.url)
  const search = new URLSearchParams(url.search)
  const params = search.getAll('foo')
  return c.json(params)
})

export default app

If it is annoying, feel free to close this issue.

spencerwooo commented 2 years ago

Thanks! I just came across Hono today, and seeing its performance advantages over itty-router - I may switch over when I have time ;)

Cheers, and thanks for letting me know.

(I'll keep this open when I eventually refactor the project to use Hono or get multiple queries implemented.)