Skip to content

Commit 427b65f

Browse files
committed
refactor(http): extract logic into constructRedirectPath
This allows us to easily test our redirect path construction logic where we get the relative path, the query string and construct a redirect path. By extracting this from `redirect`, we can easily test this logic in a unit test. I did this so we could test some logic where slashes in query strings should be made human-friendly for users.
1 parent b3cf4c3 commit 427b65f

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

src/node/http.ts

+15-3
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,20 @@ export const relativeRoot = (originalUrl: string): string => {
138138
return normalize("./" + (depth > 1 ? "../".repeat(depth - 1) : ""))
139139
}
140140

141+
/**
142+
* A helper function to construct a redirect path based on
143+
* an Express Request, query and a path to redirect to.
144+
*
145+
* Redirect path is relative to `/${to}`.
146+
*/
147+
export const constructRedirectPath = (req: express.Request, query: qs.ParsedQs, to: string): string => {
148+
const relativePath = normalize(`${relativeRoot(req.originalUrl)}/${to}`, true)
149+
const queryString = qs.stringify(query)
150+
const redirectPath = `${relativePath}${queryString ? `?${queryString}` : ""}`
151+
152+
return redirectPath
153+
}
154+
141155
/**
142156
* Redirect relatively to `/${to}`. Query variables on the current URI will be
143157
* preserved. `to` should be a simple path without any query parameters
@@ -156,9 +170,7 @@ export const redirect = (
156170
}
157171
})
158172

159-
const relativePath = normalize(`${relativeRoot(req.originalUrl)}/${to}`, true)
160-
const queryString = qs.stringify(query)
161-
const redirectPath = `${relativePath}${queryString ? `?${queryString}` : ""}`
173+
const redirectPath = constructRedirectPath(req, query, to)
162174
logger.debug(`redirecting from ${req.originalUrl} to ${redirectPath}`)
163175
res.redirect(redirectPath)
164176
}

0 commit comments

Comments
 (0)