boa icon indicating copy to clipboard operation
boa copied to clipboard

TryFromJsValue

Open lastmjs opened this issue 3 years ago • 4 comments

Working on Azle which is a JS environment for the Internet Computer, I need to have a general solution for converting JsValues into arbitrary types. I have been attempting to do this using serde_json::from_value(js_value.to_json(& mut context).unwrap()).unwrap() which works in many cases, but breaks down sometimes (for example with undefined and bigint). It's also a more complicated developer experience and probably less performant than a direct conversion from JsValue to an arbitrary type would be.

The below is from this comment: https://github.com/boa-dev/boa/issues/1961#issuecomment-1075673692

This would make a lot of sense, yes. We could have a TryFromJsValue trait that would receive a context and a JsValue and try to perform the conversion. Just thinking out loud, but I could imagine a similar API to the Serializa/Deserialize APIs in serde.

I would like to start a discussion on some sort of TryFromJsValue. Is this something you think boa could/would want to support? If so, what should the API look like?

I would like this functionality ASAP and so if it would be accepted and I could receive some guidance, I am happy to do the work. If it's relatively simple for the maintainers to go ahead and do it then I am happy with that as well. Just hope this can be done.

Thanks!

lastmjs avatar Mar 24 '22 17:03 lastmjs

To add to this, going the other way would also be really nice. I would like to be able to convert values of arbitrary Rust types into JsValues, and that capability seems limited as of right now.

lastmjs avatar Mar 24 '22 17:03 lastmjs

To add to this, going the other way would also be really nice. I would like to be able to convert values of arbitrary Rust types into JsValues, and that capability seems limited as of right now.

Well, this is already possible for base Rust types. Maybe there should be another trait to make it simpler.

In general, I imagine this to work similarly to the Serialize and Deserialize traits, and they might even be derivable if we create the proper logic. I guess the best approach is to check how is Serde doing it, and try to inspire the solution on it.

Razican avatar Mar 24 '22 18:03 Razican

Having this API implemented would solve a host of issues for my project: https://github.com/demergent-labs/azle/issues/142

I am ready to start working on this as soon as tomorrow, it's a major blocking issue for me. If you would accept a PR let me know, and I would love some guidance. If you want to wait for whatever reason, I would really appreciate some initial guidance as I will need to implement this functionality for myself no matter what.

lastmjs avatar Mar 29 '22 20:03 lastmjs

I've started working on this, considering two traits IntoJsValue and FromJsValue.

lastmjs avatar Mar 30 '22 14:03 lastmjs