Skip to content

Commit 66181d2

Browse files
authored
cache : serialize Query only if needed, avoid throwing error (#4441)
1 parent 156a5ec commit 66181d2

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

lib/core/util.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,13 +102,24 @@ function isBlobLike (object) {
102102
}
103103
}
104104

105+
/**
106+
* @param {string} url The path to check for query strings or fragments.
107+
* @returns {boolean} Returns true if the path contains a query string or fragment.
108+
*/
109+
function pathHasQueryOrFragment (url) {
110+
return (
111+
url.includes('?') ||
112+
url.includes('#')
113+
)
114+
}
115+
105116
/**
106117
* @param {string} url The URL to add the query params to
107118
* @param {import('node:querystring').ParsedUrlQueryInput} queryParams The object to serialize into a URL query string
108119
* @returns {string} The URL with the query params added
109120
*/
110121
function serializePathWithQuery (url, queryParams) {
111-
if (url.includes('?') || url.includes('#')) {
122+
if (pathHasQueryOrFragment(url)) {
112123
throw new Error('Query params cannot be passed when url already contains "?" or "#".')
113124
}
114125

@@ -924,6 +935,7 @@ module.exports = {
924935
assertRequestHandler,
925936
getSocketInfo,
926937
isFormDataLike,
938+
pathHasQueryOrFragment,
927939
serializePathWithQuery,
928940
addAbortListener,
929941
isValidHTTPToken,

lib/util/cache.js

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
'use strict'
22

33
const {
4-
safeHTTPMethods
4+
safeHTTPMethods,
5+
pathHasQueryOrFragment
56
} = require('../core/util')
67

78
const { serializePathWithQuery } = require('../core/util')
@@ -14,12 +15,10 @@ function makeCacheKey (opts) {
1415
throw new Error('opts.origin is undefined')
1516
}
1617

17-
let fullPath
18-
try {
19-
fullPath = serializePathWithQuery(opts.path || '/', opts.query)
20-
} catch (error) {
21-
// If fails (path already has query params), use as-is
22-
fullPath = opts.path || '/'
18+
let fullPath = opts.path || '/'
19+
20+
if (opts.query && !pathHasQueryOrFragment(opts.path)) {
21+
fullPath = serializePathWithQuery(fullPath, opts.query)
2322
}
2423

2524
return {

0 commit comments

Comments
 (0)