Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/fresh-lights-battle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"devalue": patch
---

fix: allow custom revivers to revive things serialized by builtin reducers
8 changes: 7 additions & 1 deletion src/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,13 @@ export function unflatten(parsed, revivers) {

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

switch (type) {
Expand Down
22 changes: 21 additions & 1 deletion test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -582,7 +582,27 @@ const fixtures = {
assert.equal(obj1.value.bar.value.answer, 42);
}
}
])(new Foo({ bar: new Bar({ answer: 42 }) }))
])(new Foo({ bar: new Bar({ answer: 42 }) })),

custom_fallback: ((date) => [
{
name: 'Custom fallback',
value: date,
js: "new Date('')",
json: '[["Date",""]]',
replacer: (value) => value instanceof Date && `new Date('')`,
reducers: {
Date: (value) => value instanceof Date && '',
},
revivers: {
Date: (value) => new Date(value)
},
validate: (obj) => {
assert.ok(obj instanceof Date);
assert.ok(isNaN(obj.getDate()));
}
}
])(new Date('invalid'))
};

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