Skip to content

Commit a5640d4

Browse files
Add an API to pass an Object Literal for the write converter
When calling "Cookies.withConverter", you can pass either a function to use as the read converter, or an Object Literal with the properties "read" and "write".
1 parent d832048 commit a5640d4

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

src/js.cookie.js

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,12 @@
5555
}
5656
} catch (e) {}
5757

58-
value = encodeURIComponent(String(value));
59-
value = value.replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
58+
if (!converter.write) {
59+
value = encodeURIComponent(String(value))
60+
.replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
61+
} else {
62+
value = converter.write(value, key);
63+
}
6064

6165
key = encodeURIComponent(String(key));
6266
key = key.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent);
@@ -94,7 +98,9 @@
9498
}
9599

96100
try {
97-
cookie = converter && converter(cookie, name) || cookie.replace(rdecode, decodeURIComponent);
101+
cookie = converter.read ?
102+
converter.read(cookie, name) : converter(cookie, name) ||
103+
cookie.replace(rdecode, decodeURIComponent);
98104

99105
if (this.json) {
100106
try {
@@ -135,5 +141,5 @@
135141
return api;
136142
}
137143

138-
return init();
144+
return init(function () {});
139145
}));

test/tests.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,28 @@ QUnit.test('should be able to conditionally decode a single malformed cookie', f
279279
assert.strictEqual(document.cookie, '', 'should remove everything');
280280
});
281281

282+
// github.com/js-cookie/js-cookie/issues/70
283+
QUnit.test('should be able to create a write decoder', function (assert) {
284+
assert.expect(1);
285+
Cookies.withConverter({
286+
write: function (value) {
287+
return value.replace('+', '%2B');
288+
}
289+
}).set('c', '+');
290+
assert.strictEqual(document.cookie, 'c=%2B', 'should call the write converter');
291+
});
292+
293+
QUnit.test('should be able to use read and write decoder', function (assert) {
294+
assert.expect(1);
295+
document.cookie = 'c=%2B';
296+
var cookies = Cookies.withConverter({
297+
read: function (value) {
298+
return value.replace('%2B', '+');
299+
}
300+
});
301+
assert.strictEqual(cookies.get('c'), '+', 'should call the read converter');
302+
});
303+
282304
QUnit.module('JSON handling', lifecycle);
283305

284306
QUnit.test('Number', function (assert) {

0 commit comments

Comments
 (0)