#decode optional field as Optional

1 messages · Page 1 of 1 (latest)

rapid bane
#

Sorry for the outright question, but I can't seem to figure it out myself:
Let's say I have the following type:

type PartialUser {
  PartialUser(
    id: Optional(Int), 
    username: Optional(String),
    // double optional -> first optional gives info           whether the data was fetched
    // 2nd optional is null data
    bio: Optional(Optional(String))
)}

Now for when I know that I will get back valid data I might use something like (maybe this is also wrong 🙂 ):
(User is like PartialUser but without the first level of optional.)

fn valid_user_decoder() {
  {
    use id <- decode.field(0, decode.int)
    use username <- decode.field(1, decode.string)
    use bio <- decode.field(2, decode.optional(decode.string))
    decode.success(User(id:, username:, bio:))
  }
}

But how do you now write something similar for PartialUser?
One (probably) wrong approach is to do:

fn partial_user_decoder() {
  {
    use id <- decode.field(0, decode.optional(decode.int))
    use username <- decode.field(1, decode.optional(decode.string))
    use bio <- decode.field(2, decode.optional(decode.optional(decode.string)))
    decode.success(PartialUser(id:, username:, bio:))
  }
}

We need some way to communicate how my None value looks like. I'm interacting with a db so my None value is simply the String "NULL" but where here do I encode such info as (for example) id is already trying to use decode.int

rapid bane
#

For context I'm trying to decode results from pog:|> pog.returning(partial_user_decoder())

unkempt crater
#

If you want to handle extra things like the string NULL, you'll have to write your own optional decoder. decode.optional only handles null and undefined

rapid bane