Skip to content

Commit

Permalink
Update for new decoder API
Browse files Browse the repository at this point in the history
  • Loading branch information
lpil committed Dec 22, 2024
1 parent 53795cb commit 07c62e7
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 14 deletions.
6 changes: 3 additions & 3 deletions examples/03-working-with-json/gleam.toml
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
name = "app"
version = "1.0.0"
description = "A Wisp example"
gleam = ">= 0.32.0"
gleam = ">= 1.4.0"

[dependencies]
gleam_stdlib = ">= 0.30.0 and < 2.0.0"
gleam_stdlib = ">= 0.51.0 and < 2.0.0"
wisp = { path = "../.." }
gleam_json = ">= 2.0.0 and < 3.0.0"
gleam_json = ">= 2.2.0 and < 3.0.0"
gleam_erlang = ">= 0.23.0 and < 2.0.0"
mist = ">= 4.0.0 and < 5.0.0"
gleam_http = ">= 3.5.0 and < 4.0.0"
Expand Down
18 changes: 7 additions & 11 deletions examples/03-working-with-json/src/app/router.gleam
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import app/web
import gleam/dynamic.{type Dynamic}
import gleam/dynamic/decode
import gleam/http.{Post}
import gleam/json
import gleam/result
Expand All @@ -15,14 +15,10 @@ pub type Person {
// dynamic values [1].
//
// [1]: https://hexdocs.pm/gleam_stdlib/gleam/dynamic.html
fn decode_person(json: Dynamic) -> Result(Person, dynamic.DecodeErrors) {
let decoder =
dynamic.decode2(
Person,
dynamic.field("name", dynamic.string),
dynamic.field("is-cool", dynamic.bool),
)
decoder(json)
fn person_decoder() -> decode.Decoder(Person) {
use name <- decode.field("name", decode.string)
use is_cool <- decode.field("is-cool", decode.bool)
decode.success(Person(name:, is_cool:))
}

pub fn handle_request(req: Request) -> Response {
Expand All @@ -36,8 +32,8 @@ pub fn handle_request(req: Request) -> Response {
use json <- wisp.require_json(req)

let result = {
// The dynamic value can be decoded into a `Person` value.
use person <- result.try(decode_person(json))
// The JSON data can be decoded into a `Person` value.
use person <- result.try(decode.run(json, person_decoder()))

// And then a JSON response can be created from the person.
let object =
Expand Down

0 comments on commit 07c62e7

Please sign in to comment.