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

perf(helper/cookie): fast-path for name specified #3608

Merged
merged 6 commits into from
Nov 2, 2024
Merged
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
8 changes: 8 additions & 0 deletions src/utils/cookie.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ describe('Parse cookie', () => {
expect(cookie['tasty_cookie']).toBeUndefined()
})

it('Should parse one cookie specified by name even if it is not found', () => {
const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry '
const cookie: Cookie = parse(cookieString, 'no_such_cookie')
expect(cookie['yummy_cookie']).toBeUndefined()
expect(cookie['tasty_cookie']).toBeUndefined()
expect(cookie['no_such_cookie']).toBeUndefined()
})

it('Should parse cookies with no value', () => {
const cookieString = 'yummy_cookie=; tasty_cookie = ; best_cookie= ; last_cookie=""'
const cookie: Cookie = parse(cookieString)
Expand Down
20 changes: 14 additions & 6 deletions src/utils/cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,17 +77,22 @@ const validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/
const validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/

export const parse = (cookie: string, name?: string): Cookie => {
if (name && cookie.indexOf(name) === -1) {
// Fast-path: return immediately if the demanded-key is not in the cookie string
return {}
}
const pairs = cookie.trim().split(';')
return pairs.reduce((parsedCookie, pairStr) => {
const parsedCookie: Cookie = {}
for (let pairStr of pairs) {
pairStr = pairStr.trim()
const valueStartPos = pairStr.indexOf('=')
if (valueStartPos === -1) {
return parsedCookie
continue
}

const cookieName = pairStr.substring(0, valueStartPos).trim()
if ((name && name !== cookieName) || !validCookieNameRegEx.test(cookieName)) {
return parsedCookie
continue
}

let cookieValue = pairStr.substring(valueStartPos + 1).trim()
Expand All @@ -96,10 +101,13 @@ export const parse = (cookie: string, name?: string): Cookie => {
}
if (validCookieValueRegEx.test(cookieValue)) {
parsedCookie[cookieName] = decodeURIComponent_(cookieValue)
if (name) {
// Fast-path: return only the demanded-key immediately. Other keys are not needed.
break
}
}

return parsedCookie
}, {} as Cookie)
}
return parsedCookie
}

export const parseSigned = async (
Expand Down
Loading