cloudflare / chanfana

OpenAPI 3 and 3.1 schema generator and validator for Hono, itty-router and more!
https://chanfana.pages.dev
MIT License
288 stars 38 forks source link

Query parameter extraction Incomplete with Question Mark (?) #49

Closed oscaramos closed 1 year ago

oscaramos commented 1 year ago

The extractQueryParameters function may not be returning all query parameters in scenarios where a parameter value contains a question mark (?).

For a demonstration, please refer to and execute the code provided here.

export function extractQueryParameters(request: { url: string }): Record<string, any> {
  const url = decodeURIComponent(request.url).split('?')

  if (url.length === 1) {
    return {}
  }

  const query = url[1]

  const params: Record<string, any> = {}
  for (const param of query.split('&')) {
    const paramSplitted = param.split('=')
    const key = paramSplitted[0]
    const value = paramSplitted[1]

    if (params[key] === undefined) {
      params[key] = value
    } else if (!Array.isArray(params[key])) {
      params[key] = [params[key], value]
    } else {
      params[key].push(value)
    }
  }

  return params
}

const baseURL = "http://example.com?"
const passingCase = baseURL + encodeURIComponent("question=What is the answer to life, the universe and everything&answer=42")
const failingCase = baseURL + encodeURIComponent("question=What is the answer to life, the universe and everything?&answer=42")

console.log("URLs")
console.log("Passing case url: ", passingCase)
console.log("Failing case url: ", failingCase)

console.log("\nQuery Parameters")
console.log("Passing: ", extractQueryParameters({ url: passingCase }))
console.log("Failing: ", extractQueryParameters({ url: failingCase }))
G4brym commented 1 year ago

Hey @oscaramos thanks for contributing this fix Your changes been bundled in the latest release (v0.1.4)