rawhat / mist

gleam HTTP server. because it glistens on a web
Apache License 2.0
260 stars 11 forks source link

Recommendation for handling state #18

Closed bcpeinhardt closed 1 year ago

bcpeinhardt commented 1 year ago

Hey there! I've set up a little todo rest api example. I have an IdGen type for generating my ID's, and I'd like to be able to use the updated verison for each new request. It's currently structured like

pub fn main() {
  use conn <- sqlight.with_connection("file:db.sqlite3")
  let todo_id_gen: IdGen(Todo) = IdGen(0)
  let state = State(conn, todo_id_gen)
  let init_service = fn(req) {
    let #(resp, state) = router(req, state)
    resp
  }

  let assert Ok(_) =
    mist.run_service(8080, init_service, max_body_limit: 4_000_000)
  process.sleep_forever()
}

so the updated state isn't getting used. How would you recommend passing updated state to request handlers?

rawhat commented 1 year ago

To make sure I'm understanding correctly, is the idea that your todo_id_gen gives back a new value each time it's called?

If the answer to my above is correct, I'd imagine you'll want to make an actor to represent your IdGen logic. You would store the handler in your State, and send a message to get a new id with something like this. That message handler would increment its internal state.

Let me know if I'm mistaken, or you have any questions about that.

bcpeinhardt commented 1 year ago

Gotcha, I'm super new to OTP so it's time I figured it out (I'm assuming that's what you mean by actor). Basically, the id module has a function that will use the IdGen struct to give back a new Id and a new IdGen, it needs refactoring but it's essentially the same.

rawhat commented 1 year ago

Closing this for now, feel free to re-open if needed!