[learning Rust]

Something I am realizing right now is that if I am to start using Rust for my web apps, I am going to have to be pretty careful about JSON ingest, specifically handling `NULL`s and other ambiguous typing that comes with many APIs.

When I get JSON data and parse it, I need the data to be very well organized, properly typed, and predictable.

Q: For those who are Rust devs (especially those of you who use Yew+Wasm), when you receive JSON into your application do you usually parse first into a JSON struct/enum first to sanitize then construct your target or do you parse directly into your target strct/enum?

#askNostr #Rust #webDev

Reply to this note

Please Login to reply.

Discussion

Not yew and wasm, but lots of Rust. Typically you deserialize directly into your type, and then maybe have an additional validation method on it if the shape is not enough.

In practice it’s not really that bad when it comes to types. You can set Serde to ignore unknown fields to deal with APIs that throw the jungle together with the monkey and the banana. But yes, if something that you need out of the API can be NULL, that should be an Option on Rust side.

But that’s a win. Right? Right? 😂😅

Oh! Of course! Rust itself doesn't have `null`, but I can totally make more falsy Options, and that would enable me to have a lot more control about exceptions, like "missing," (API doesn't know it should be there) "empty," (API failed to give a value) or actually `false` (API knew it should be there and set it to `false`) being different, usable cases.

That should be better code than my go-to of negative INTs to communicate a specific error type.

Yes, exactly! Rust lets you encode a lot more into your types than what you would normally be used to in other languages.

Regarding errors, if there’s semantic meaning attached to the negative ints in the API, you might want to have an Error type that captures that meaning on Rust side. Look into the thiserror crate that lets you easily spin up custom error types.

Yes. I started creating an online learning app for myself and encoded the negative to mean things like "never set," "user deleted," "missing data," etc. I don't think think I've used more (or lesser? 🤷‍♂️) than -3 in my code, but nothing prevents my using the whole range of an i8 in rust while also having robust exception handling.