Skip to content

Commit 5c26c0d

Browse files
fix: allow custom revivers to revive things serialized by buitin reducers (#118)
1 parent 8b0c28d commit 5c26c0d

File tree

3 files changed

+33
-2
lines changed

3 files changed

+33
-2
lines changed

.changeset/fresh-lights-battle.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"devalue": patch
3+
---
4+
5+
fix: allow custom revivers to revive things serialized by builtin reducers

src/parse.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,13 @@ export function unflatten(parsed, revivers) {
6060

6161
const reviver = revivers?.[type];
6262
if (reviver) {
63-
return (hydrated[index] = reviver(hydrate(value[1])));
63+
let i = value[1];
64+
if (typeof i !== 'number') {
65+
// if it's not a number, it was serialized by a builtin reviver
66+
// so we need to munge it into the format expected by a custom reviver
67+
i = values.push(value[1]) - 1;
68+
}
69+
return (hydrated[index] = reviver(hydrate(i)));
6470
}
6571

6672
switch (type) {

test/test.js

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -582,7 +582,27 @@ const fixtures = {
582582
assert.equal(obj1.value.bar.value.answer, 42);
583583
}
584584
}
585-
])(new Foo({ bar: new Bar({ answer: 42 }) }))
585+
])(new Foo({ bar: new Bar({ answer: 42 }) })),
586+
587+
custom_fallback: ((date) => [
588+
{
589+
name: 'Custom fallback',
590+
value: date,
591+
js: "new Date('')",
592+
json: '[["Date",""]]',
593+
replacer: (value) => value instanceof Date && `new Date('')`,
594+
reducers: {
595+
Date: (value) => value instanceof Date && '',
596+
},
597+
revivers: {
598+
Date: (value) => new Date(value)
599+
},
600+
validate: (obj) => {
601+
assert.ok(obj instanceof Date);
602+
assert.ok(isNaN(obj.getDate()));
603+
}
604+
}
605+
])(new Date('invalid'))
586606
};
587607

588608
for (const [name, tests] of Object.entries(fixtures)) {

0 commit comments

Comments
 (0)