34 lines
768 B
Gleam
34 lines
768 B
Gleam
import gleam/dynamic/decode.{type Decoder}
|
|
import gleam/json.{type Json}
|
|
|
|
pub type TransactionType {
|
|
Purchase
|
|
Sell
|
|
}
|
|
|
|
pub fn parse(value: String) -> Result(TransactionType, Nil) {
|
|
case value {
|
|
"PURCHASE" -> Ok(Purchase)
|
|
"SELL" -> Ok(Sell)
|
|
_ -> Error(Nil)
|
|
}
|
|
}
|
|
|
|
pub fn decoder() -> Decoder(TransactionType) {
|
|
use value <- decode.then(decode.string)
|
|
case parse(value) {
|
|
Ok(transaction_type) -> decode.success(transaction_type)
|
|
Error(Nil) -> decode.failure(Purchase, "TransactionType")
|
|
}
|
|
}
|
|
|
|
pub fn to_string(transaction_type: TransactionType) -> String {
|
|
case transaction_type {
|
|
Purchase -> "PURCHASE"
|
|
Sell -> "SELL"
|
|
}
|
|
}
|
|
|
|
pub fn encode(transaction_type: TransactionType) -> Json {
|
|
json.string(to_string(transaction_type))
|
|
}
|