Hello everyone. I'm pretty new to Gleam. I want to decode a DateTime string into DateTime value but I can't because the result of datetime.from_string is a Result. I searched everywhere for a solution to no avail. Please help me find a solution. Here's the code:
import gleam/dynamic/decode
import gleam/json
import gleam/option.{type Option, None, Some}
import tempo.{type DateTime}
import tempo/datetime
pub type Link {
Link(
id: String,
original_link: String,
short_link: String,
clicks: Int,
user_id: Option(String),
wait_time: Int,
password: Option(String),
created_at: DateTime,
updated_at: DateTime,
accessed_at: DateTime,
)
}
pub fn json_to_link(json_string: String) -> Result(Link, json.DecodeError) {
let link_decoder = {
use id <- decode.field("id", decode.string)
use original_link <- decode.field("original_link", decode.string)
use short_link <- decode.field("short_link", decode.string)
use clicks <- decode.field("clicks", decode.int)
use password <- decode.optional_field("password", "", decode.string)
use user_id <- decode.optional_field("user_id", "", decode.string)
use wait_time <- decode.field("wait_time", decode.int)
use created_at <- decode.field("created_at", decode.string)
use updated_at <- decode.field("updated_at", decode.string)
use accessed_at <- decode.field("accessed_at", decode.string)
let password = case password {
"" -> None
_ -> Some(password)
}
let user_id = case user_id {
"" -> None
_ -> Some(user_id)
}
// I WANNA CONVERT created_at, updated_at, accessed_at from String to DateTime here
decode.success(Link(
id:,
original_link:,
short_link:,
clicks:,
password:,
user_id:,
wait_time:,
created_at:,
updated_at:,
accessed_at:,
))
}
json.parse(from: json_string, using: link_decoder)
}
Thanks in advance.