Unverified Commit 5c72663c authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Ensure params in query are updated for custom-routes (#9797)

* Add handling for params in destination query

* Update describe name
parent 4f0c74c5
...@@ -428,11 +428,23 @@ export default class Server { ...@@ -428,11 +428,23 @@ export default class Server {
name: `${route.type} ${route.source} route`, name: `${route.type} ${route.source} route`,
fn: async (_req, res, params, _parsedUrl) => { fn: async (_req, res, params, _parsedUrl) => {
const parsedDestination = parseUrl(route.destination, true) const parsedDestination = parseUrl(route.destination, true)
const destQuery = parsedDestination.query
let destinationCompiler = compilePathToRegex( let destinationCompiler = compilePathToRegex(
`${parsedDestination.pathname!}${parsedDestination.hash || ''}` `${parsedDestination.pathname!}${parsedDestination.hash || ''}`
) )
let newUrl let newUrl
Object.keys(destQuery).forEach(key => {
const val = destQuery[key]
if (
typeof val === 'string' &&
val.startsWith(':') &&
params[val.substr(1)]
) {
destQuery[key] = params[val.substr(1)]
}
})
try { try {
newUrl = destinationCompiler(params) newUrl = destinationCompiler(params)
} catch (err) { } catch (err) {
...@@ -456,6 +468,7 @@ export default class Server { ...@@ -456,6 +468,7 @@ export default class Server {
...parsedDestination, ...parsedDestination,
pathname: parsedNewUrl.pathname, pathname: parsedNewUrl.pathname,
hash: parsedNewUrl.hash, hash: parsedNewUrl.hash,
search: undefined,
}) })
) )
res.statusCode = route.statusCode || DEFAULT_REDIRECT_STATUS res.statusCode = route.statusCode || DEFAULT_REDIRECT_STATUS
...@@ -470,6 +483,7 @@ export default class Server { ...@@ -470,6 +483,7 @@ export default class Server {
return { return {
finished: false, finished: false,
pathname: newUrl, pathname: newUrl,
query: parsedDestination.query,
} }
}, },
} as Route } as Route
...@@ -795,6 +809,7 @@ export default class Server { ...@@ -795,6 +809,7 @@ export default class Server {
const curUrl = parseUrl(req.url!, true) const curUrl = parseUrl(req.url!, true)
req.url = formatUrl({ req.url = formatUrl({
...curUrl, ...curUrl,
search: undefined,
query: { query: {
...curUrl.query, ...curUrl.query,
...query, ...query,
......
...@@ -11,6 +11,7 @@ export type RouteMatch = (pathname: string | undefined) => false | Params ...@@ -11,6 +11,7 @@ export type RouteMatch = (pathname: string | undefined) => false | Params
type RouteResult = { type RouteResult = {
finished: boolean finished: boolean
pathname?: string pathname?: string
query?: { [k: string]: string }
} }
export type Route = { export type Route = {
...@@ -105,6 +106,13 @@ export default class Router { ...@@ -105,6 +106,13 @@ export default class Router {
parsedUrlUpdated.pathname = result.pathname parsedUrlUpdated.pathname = result.pathname
} }
if (result.query) {
parsedUrlUpdated.query = {
...parsedUrlUpdated.query,
...result.query,
}
}
// check filesystem // check filesystem
if (route.check === true) { if (route.check === true) {
for (const fsRoute of this.fsRoutes) { for (const fsRoute of this.fsRoutes) {
......
...@@ -47,6 +47,10 @@ module.exports = { ...@@ -47,6 +47,10 @@ module.exports = {
source: '/params/:something', source: '/params/:something',
destination: '/with-params', destination: '/with-params',
}, },
{
source: '/query-rewrite/:section/:name',
destination: '/with-params?first=:section&second=:name',
},
{ {
source: '/hidden/_next/:path*', source: '/hidden/_next/:path*',
destination: '/_next/:path*', destination: '/_next/:path*',
...@@ -112,6 +116,10 @@ module.exports = { ...@@ -112,6 +116,10 @@ module.exports = {
source: '/to-external', source: '/to-external',
destination: 'https://google.com', destination: 'https://google.com',
}, },
{
source: '/query-redirect/:section/:name',
destination: '/with-params?first=:section&second=:name',
},
] ]
}, },
}, },
......
...@@ -4,6 +4,7 @@ import url from 'url' ...@@ -4,6 +4,7 @@ import url from 'url'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
import fs from 'fs-extra' import fs from 'fs-extra'
import { join } from 'path' import { join } from 'path'
import cheerio from 'cheerio'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { import {
launchApp, launchApp,
...@@ -28,6 +29,8 @@ let stdout = '' ...@@ -28,6 +29,8 @@ let stdout = ''
let appPort let appPort
let app let app
const escapeRegex = str => str.replace(/[|\\{}()[\]^$+*?.-]/g, '\\$&')
const runTests = (isDev = false) => { const runTests = (isDev = false) => {
it('should handle one-to-one rewrite successfully', async () => { it('should handle one-to-one rewrite successfully', async () => {
const html = await renderViaHTTP(appPort, '/first') const html = await renderViaHTTP(appPort, '/first')
...@@ -119,6 +122,33 @@ const runTests = (isDev = false) => { ...@@ -119,6 +122,33 @@ const runTests = (isDev = false) => {
expect(html).toMatch(/hi there/) expect(html).toMatch(/hi there/)
}) })
it('should allow params in query for rewrite', async () => {
const html = await renderViaHTTP(appPort, '/query-rewrite/hello/world?a=b')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').html()).query).toEqual({
first: 'hello',
second: 'world',
a: 'b',
section: 'hello',
name: 'world',
})
})
it('should allow params in query for redirect', async () => {
const res = await fetchViaHTTP(
appPort,
'/query-redirect/hello/world?a=b',
undefined,
{
redirect: 'manual',
}
)
const { pathname, query } = url.parse(res.headers.get('location'), true)
expect(res.status).toBe(307)
expect(pathname).toBe('/with-params')
expect(query).toEqual({ first: 'hello', second: 'world' })
})
it('should overwrite param values correctly', async () => { it('should overwrite param values correctly', async () => {
const html = await renderViaHTTP(appPort, '/test-overwrite/first/second') const html = await renderViaHTTP(appPort, '/test-overwrite/first/second')
expect(html).toMatch(/this-should-be-the-value/) expect(html).toMatch(/this-should-be-the-value/)
...@@ -285,6 +315,15 @@ const runTests = (isDev = false) => { ...@@ -285,6 +315,15 @@ const runTests = (isDev = false) => {
source: '/to-external', source: '/to-external',
statusCode: 307, statusCode: 307,
}, },
{
destination: '/with-params?first=:section&second=:name',
regex: normalizeRegEx(
'^\\/query-redirect(?:\\/([^\\/]+?))(?:\\/([^\\/]+?))$'
),
regexKeys: ['section', 'name'],
source: '/query-redirect/:section/:name',
statusCode: 307,
},
], ],
rewrites: [ rewrites: [
{ {
...@@ -355,6 +394,14 @@ const runTests = (isDev = false) => { ...@@ -355,6 +394,14 @@ const runTests = (isDev = false) => {
regex: normalizeRegEx('^\\/params(?:\\/([^\\/]+?))$'), regex: normalizeRegEx('^\\/params(?:\\/([^\\/]+?))$'),
regexKeys: ['something'], regexKeys: ['something'],
}, },
{
destination: '/with-params?first=:section&second=:name',
regex: normalizeRegEx(
'^\\/query-rewrite(?:\\/([^\\/]+?))(?:\\/([^\\/]+?))$'
),
regexKeys: ['section', 'name'],
source: '/query-rewrite/:section/:name',
},
{ {
destination: '/_next/:path*', destination: '/_next/:path*',
regex: normalizeRegEx( regex: normalizeRegEx(
...@@ -388,7 +435,9 @@ const runTests = (isDev = false) => { ...@@ -388,7 +435,9 @@ const runTests = (isDev = false) => {
for (const route of [...manifest.redirects, ...manifest.rewrites]) { for (const route of [...manifest.redirects, ...manifest.rewrites]) {
expect(cleanStdout).toMatch( expect(cleanStdout).toMatch(
new RegExp(`${route}.*?${route.destination}`) new RegExp(
`${escapeRegex(route.source)}.*?${escapeRegex(route.destination)}`
)
) )
} }
}) })
...@@ -413,7 +462,7 @@ describe('Custom routes', () => { ...@@ -413,7 +462,7 @@ describe('Custom routes', () => {
runTests(true) runTests(true)
}) })
describe('production mode', () => { describe('server mode', () => {
beforeAll(async () => { beforeAll(async () => {
const { stdout: buildStdout } = await nextBuild(appDir, [], { const { stdout: buildStdout } = await nextBuild(appDir, [], {
stdout: true, stdout: true,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment