Skip to content

Commit

Permalink
perf: only call removeHeader when needed (#244)
Browse files Browse the repository at this point in the history
* only call removeHeader when needed

* clear in all conditions
  • Loading branch information
gurgunday authored Aug 2, 2023
1 parent 9cbcc17 commit 2165139
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ function fastifyCookieSetCookie (reply, name, value, options) {

if (reply[kReplySetCookiesHookRan]) {
setCookies(reply)
reply[kReplySetCookies].clear()
}

return reply
Expand Down Expand Up @@ -71,14 +70,17 @@ function onReqHandlerWrapper (fastify, hook) {

function setCookies (reply) {
let setCookie = reply.getHeader('Set-Cookie')
const setCookieIsUndefined = setCookie === undefined

/* istanbul ignore else */
if (setCookie === undefined) {
if (setCookieIsUndefined) {
if (reply[kReplySetCookies].size === 1) {
for (const c of reply[kReplySetCookies].values()) {
reply.header('Set-Cookie', cookie.serialize(c.name, c.value, c.opts))
}

reply[kReplySetCookies].clear()

return
}

Expand All @@ -91,14 +93,14 @@ function setCookies (reply) {
setCookie.push(cookie.serialize(c.name, c.value, c.opts))
}

reply.removeHeader('Set-Cookie')
if (!setCookieIsUndefined) reply.removeHeader('Set-Cookie')
reply.header('Set-Cookie', setCookie)
reply[kReplySetCookies].clear()
}

function fastifyCookieOnSendHandler (fastifyReq, fastifyRes, payload, done) {
if (fastifyRes[kReplySetCookies].size) {
setCookies(fastifyRes)
fastifyRes[kReplySetCookies].clear()
}

fastifyRes[kReplySetCookiesHookRan] = true
Expand Down

0 comments on commit 2165139

Please sign in to comment.