From ab16aeed140facb376010a7fcfeeee3b45a5042d Mon Sep 17 00:00:00 2001 From: Nigro Simone Date: Sun, 24 Nov 2024 16:37:50 +0100 Subject: [PATCH] fix: #68 --- src/response.js | 20 +++++++++----------- tests/tests/res/res-cookie.js | 8 ++++++++ 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/src/response.js b/src/response.js index 65f8471..3730c0d 100644 --- a/src/response.js +++ b/src/response.js @@ -601,26 +601,24 @@ module.exports = class Response extends Writable { this.app.render(view, options, done); } cookie(name, value, options) { - if(!options) { - options = {}; - } + const opt = {...(options ?? {})}; // create a new ref because we change original object (https://github.com/dimdenGD/ultimate-express/issues/68) let val = typeof value === 'object' ? "j:"+JSON.stringify(value) : String(value); - if(options.maxAge != null) { - const maxAge = options.maxAge - 0; + if(opt.maxAge != null) { + const maxAge = opt.maxAge - 0; if(!isNaN(maxAge)) { - options.expires = new Date(Date.now() + maxAge); - options.maxAge = Math.floor(maxAge / 1000); + opt.expires = new Date(Date.now() + maxAge); + opt.maxAge = Math.floor(maxAge / 1000); } } - if(options.signed) { + if(opt.signed) { val = 's:' + sign(val, this.req.secret); } - if(options.path == null) { - options.path = '/'; + if(opt.path == null) { + opt.path = '/'; } - this.append('Set-Cookie', cookie.serialize(name, val, options)); + this.append('Set-Cookie', cookie.serialize(name, val, opt)); return this; } clearCookie(name, options) { diff --git a/tests/tests/res/res-cookie.js b/tests/tests/res/res-cookie.js index eba8f2e..125a548 100644 --- a/tests/tests/res/res-cookie.js +++ b/tests/tests/res/res-cookie.js @@ -4,12 +4,20 @@ const express = require("express"); const app = express(); +const sharedOptions = { maxAge: 1000 }; + app.get('/test', (req, res) => { res.cookie('test', '1'); res.cookie('test2', '2', { maxAge: 1000 }); res.cookie('test3', '3', { maxAge: 1000, path: '/test' }); res.cookie('test4', '4', { maxAge: 1000, path: '/test', httpOnly: true }); res.cookie('test5', '5', { maxAge: 1000, path: '/test', secure: true }); + + // see: https://github.com/dimdenGD/ultimate-express/issues/68 + res.cookie('test6', '2', sharedOptions); + res.cookie('test6', '2', sharedOptions); + console.log(JSON.stringify(sharedOptions)) + res.send('test'); });