Easier Sending a File Through a Port (or double-decoding a Json value)

While working on chunked file upload (that needs slicing the file on Javascript side) I have to keep around both a raw Value of dropped files (to send through a port), and a File value (to render the UI).

In thinking how to do that with some elegance, it occurred to me that Json.Decode.mapN actually applies decoders in a loop on the same object, allowing one to produce multiple representations of the object being decoded:

fileWithRaw : Decoder (File, Value)
fileWithRaw =
    Json.Decode.map2 Tuple.pair
        File.decoder
        Json.Decode.value

Never thought of it before; somehow one defaults to thinking about decode being similar to parse that consumes the tokens it parses and creates new values. Maybe Json. in the module name makes one think of that. Perhaps it’s a mild misnomer: the module has nothing to do with neither the notation, nor decoding in the sense of processing the contents of objects. No strings are involved, and decoders only wrap references to JS objects with Elm values.

Here’s the updated Ellie from a previous discussion using this technique.

3 Likes

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.