Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: simplify handling of '//' in req.url #8

Merged
merged 1 commit into from
Jan 22, 2024
Merged
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
5 changes: 2 additions & 3 deletions lib/handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,8 @@ export const createHandler = ({
* @param {import('pg').Pool} pgPool
*/
const handler = async (req, res, pgPool) => {
// Fix the edge case: new URL('//foo', 'http://127.0.0.1') produces href "http://foo/"
const reqUrl = req.url.replace(/^\/+/, '/')
const { pathname, searchParams } = new URL(reqUrl, 'http://127.0.0.1')
// Caveat! `new URL('//foo', 'http://127.0.0.1')` would produce "http://foo/" - not what we want!
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about removing the comment and adding a test for this instead? To me that's the programming native version of this solution

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We already have a test in place, I added it in #6.

https://github.com/filecoin-station/spark-stats/blob/11fc6b1d8f96a9ff855258131620409b3e26ff56/test/handler.test.js#L54-L57

I suppose I can add another test to verify now we handle an existing route with double-slash.

I prefer to keep the comment to remind readers why we are using string concatenation instead of new URL(path, base). In my experience, it's better to be explicit.

const { pathname, searchParams } = new URL(`http://127.0.0.1${req.url}`)
const segs = pathname.split('/').filter(Boolean)
if (req.method === 'GET' && segs[0] === 'retrieval-success-rate' && segs.length === 1) {
await getStatsWithFilterAndCaching(
Expand Down