Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/redirect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,22 @@ export class Redirect extends Macroable {
#sendResponse(url: string, query: Record<string, any>) {
const stringified = this.#qs.stringify(query)

url = stringified ? `${url}?${stringified}` : url
if (stringified) {
/**
* Keep the fragment at the end and join with the query string
* the url may already have
*/
const hashIndex = url.indexOf('#')
const hash = hashIndex === -1 ? '' : url.slice(hashIndex)
const base = hashIndex === -1 ? url : url.slice(0, hashIndex)
const separator = !base.includes('?')
? '?'
: base.endsWith('?') || base.endsWith('&')
? ''
: '&'

url = `${base}${separator}${stringified}${hash}`
}
debug('redirecting to url "%s"', url)

this.#response.location(encodeUrl(url))
Expand Down
14 changes: 14 additions & 0 deletions tests/redirect.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,20 @@ test.group('Redirect', () => {
assert.equal(header.location, '/posts/1')
})

test('append query string to a url that already has one', ({ assert }) => {
const response = new HttpResponseFactory().merge({ encryption, router }).create()
response.redirect().withQs({ success: 1 }).toPath('/users?page=2')

assert.equal(response.getHeader('location'), '/users?page=2&success=1')
})

test('add query string before the url fragment', ({ assert }) => {
const response = new HttpResponseFactory().merge({ encryption, router }).create()
response.redirect().withQs({ success: 1 }).toPath('/users?page=2#list')

assert.equal(response.getHeader('location'), '/users?page=2&success=1#list')
})

test('encode route params before redirecting', ({ assert }) => {
const route = new RouterFactory().merge({ app, encryption }).create()
route.get('/:page', 'PagesController.show').as('pages.show')
Expand Down