AlexCouch / pluvo

Pluvo is a modern web framework purely in Gleam built ontop of mist
4 stars 0 forks source link

Load request body into context #22

Closed AlexCouch closed 8 months ago

AlexCouch commented 8 months ago

Description

In order to allow people to use the body of a request, we need to easily load it into the context via the context's request object. This would make it easier to bind custom data models to the request so that apis can be created more easily.

Example

To bind data, we need to easily load the request's body behind the scenes, and then pass in the body data to the provided decoder.

pub type Post{
  Post(title: String, author: String, timestamp: String, body: String)
}

pub fn decode_post(from data: BitArray) -> Result(Post, DecodeError){
  //Convert data to json, get json data and construct new Post
  //If json not possible or expected fields do not exist, return DecodeError
}

pub fn handler(ctx: Context) -> Response{
  use post_data <- context.then(ctx |> context.bind(decode_post))
  //Use post_data, but if it doesn't exist, it'll return with an error response
}
AlexCouch commented 8 months ago

The current way to pass a decoder is a bit verbose. We can easily require a simpler function which is then passed into the proper decode function.

We should also add support for JSON binding using gleam_json

Example

pub type Post{
  Post(title: String, author: String, timestamp: String, body: String)
}

pub fn post_decoder() {
  dynamic.decode4(
    Post,
    dynamic.field(named: "title", of: dynamic.string),
    dynamic.field(named: "author", of: dynamic.string),
    dynamic.field(named: "timestamp", of: dynamic.string),
    dynamic.field(named: "body", of: dynamic.string),
  )
}

pub fn handler(ctx: Context) -> Response{
  use post_data <- context.then(ctx |> context.bind_json(post_decoder))
  //Use post_data, but if it doesn't exist, it'll return with an error response
}