Classes need to implement `toJSON` in order to be serialized
Environment
- Operating System: Windows_NT
- Node Version: v16.14.0
- Package Manager: [email protected]
Reproduction
https://stackblitz.com/edit/github-iaoyfc?file=app.vue
Describe the bug
From https://github.com/nuxt/nuxt/issues/22996
When an object is passed as a body to $fetch, the object will be automatically stringified. However, if the object created from new operation of class is passed, it does not get stringified.
Additionally, If I wrap the class object into other object, it will be stringified automatically.
If I provide a toJSON method on the class, the toJSON method is used for stringify. I found in ofetch, there is a function isJSONSerializable, one of the condition is value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function";.
Which means, everytime I want to use a class object as a body directly, do I need to define toJSON method?
Additional context
No response
Logs
No response
Thanks for making a nice reproduction.
Indeed you are expected to implement toJSON by yourself. JavaScript has no native implementation to stringify Pure classes and there might be many edge cases if we want to do this.
I think as a better DX, we can both improve docs and a warning when falling back to [object Object] wdyt?
That's good idea! Should I make pr for that?
Necessity of toJSON method is already written in README.
I agree that it's nice to have a logic to detect un-processable instance and show a warning message.
Necessity of
toJSONmethod is already written in README.I agree that it's nice to have a logic to detect un-processable instance and show a warning message.
Oh, yeah, it's already in docs! I missed it. Thank you for letting me know about it.