API: Take multiple values into account for the query (#9196)

* Take multiple values into account

* make typescript happy
This commit is contained in:
Jan Potoms 2019-10-26 20:10:06 +02:00 committed by Tim Neutkens
parent 20978af0b0
commit ab0a8647dc
3 changed files with 29 additions and 1 deletions

View file

@ -119,7 +119,15 @@ export function getQueryParser({ url }: IncomingMessage) {
const query: { [key: string]: string | string[] } = {}
for (const [key, value] of params) {
query[key] = value
if (query[key]) {
if (Array.isArray(query[key])) {
;(query[key] as string[]).push(value)
} else {
query[key] = [query[key], value]
}
} else {
query[key] = value
}
}
return query

View file

@ -0,0 +1,3 @@
export default (req, res) => {
res.status(200).send(req.query)
}

View file

@ -180,6 +180,23 @@ function runTests (serverless = false) {
expect(data).toEqual({ message: 'Parsed body' })
})
it('should return empty query object', async () => {
const data = await fetchViaHTTP(appPort, '/api/query', null, {}).then(
res => res.ok && res.json()
)
expect(data).toEqual({})
})
it('should parse query correctly', async () => {
const data = await fetchViaHTTP(
appPort,
'/api/query?a=1&b=2&a=3',
null,
{}
).then(res => res.ok && res.json())
expect(data).toEqual({ a: ['1', '3'], b: '2' })
})
it('should return empty cookies object', async () => {
const data = await fetchViaHTTP(appPort, '/api/cookies', null, {}).then(
res => res.ok && res.json()