Skip to content

Commit

Permalink
Add support for duplicate keys in parameters by adding `paramValuesAs…
Browse files Browse the repository at this point in the history
…Seq`

In contrast to `params` this returns a `Table[string, seq[string]]`.

Closes dom96#247
  • Loading branch information
torbencarstens committed Sep 18, 2023
1 parent 5c9e5d3 commit fef495a
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions jester/request.nim
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import uri, cgi, tables, logging, strutils, re, options
from sequtils import map

import jester/private/utils

Expand Down Expand Up @@ -116,6 +117,41 @@ proc params*(req: Request): Table[string, string] =
except:
logging.warn("Could not parse URL query.")

proc paramValuesAsSeq*(req: Request): Table[string, seq[string]] =
## Parameters from the pattern and the query string.
##
## This allows for duplicated keys in the query (in contrast to `params`)
if req.patternParams.isSome():
let patternParams: Table[string, string] = req.patternParams.get()
var patternParamsSeq: seq[(string, string)] = @[]
for key, val in pairs(patternParams):
patternParamsSeq.add (key, val)

# We are not url-decoding the key/value for the patternParams (matches implementation in `params`
result = sequtils.map(patternParamsSeq,
proc(entry: (string, string)): (string, seq[string]) =
(entry[0], @[entry[1]])
).toTable()
else:
result = initTable[string, seq[string]]()

var queriesToDecode: seq[string] = @[]
queriesToDecode.add query(req)

let contentType = req.headers.getOrDefault("Content-Type")
if contentType.startswith("application/x-www-form-urlencoded"):
queriesToDecode.add req.body

for query in queriesToDecode:
try:
for key, value in cgi.decodeData(query):
if result.hasKey(key):
result[key].add value
else:
result[key] = @[value]
except CgiError:
logging.warn("Incorrect query. Got: $1" % [query])

proc formData*(req: Request): MultiData =
let contentType = req.headers.getOrDefault("Content-Type")
if contentType.startsWith("multipart/form-data"):
Expand Down

0 comments on commit fef495a

Please sign in to comment.