ofetch icon indicating copy to clipboard operation
ofetch copied to clipboard

Classes need to implement `toJSON` in order to be serialized

Open jongmin4943 opened this issue 2 years ago • 4 comments

Environment

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

jongmin4943 avatar Sep 05 '23 17:09 jongmin4943

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?

pi0 avatar Sep 05 '23 18:09 pi0

That's good idea! Should I make pr for that?

jongmin4943 avatar Sep 06 '23 03:09 jongmin4943

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.

nozomuikuta avatar Sep 06 '23 05:09 nozomuikuta

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.

Oh, yeah, it's already in docs! I missed it. Thank you for letting me know about it.

jongmin4943 avatar Sep 06 '23 06:09 jongmin4943