New shard, kemal-controller

Hi,

I’m used to the rails way of doing a MVC web applications, so every time I was doing something with Kemal I had the felling of missing something, yes, a controller class.

This shard does that, it add a way to write Kemal routes in a controller class (struct in fact), but the most interesting thing it does IMO is to map the HTTP/Route parameters into method parameters, example:

struct UsersController < Kemal::Controller
  @[Get("/users")]
  def index
    "Listing all users"
  end

  @[Get("/users/:id")]
  def show(id : Int32)
    "Showing user with ID: #{id}"
  end

  @[Post("/users", auth: true)]
  def create(name : String, age : Int32, description : String?))
    "Creating user with name: #{name}, age: #{age} and description: #{description}"
  end

  private def authenticate! : Bool
    true
  end
end

Not a single release yep, API isn’t stable but may not have radical changes, meanwhile I’m using it in a not yet released project to test the API.

Shard can be found at GitHub - hugopl/kemal-controller: Controller classes for your kemal application. API docs on kemal-controller main

3 Likes

Could you just leverage URI::Params::Serializable - Crystal 1.18.2 for the form data parsing logic? It provides all the .from_www_form methods, but they are :nodoc:, but would cleanup a lot of the code even if you can’t use the Serializable module part itself.

EDIT: Doesn’t seem to support all the types you have tho. Would be easy enough to add support upstream for them if there is a use case tho.

Athena and Spider Gazelle do something similar as well. Makes me wonder if there’s an abstraction that could be figured out to share the API versus having n different implementations of essentially the same thing. Tho main challenge there I suppose is there’s not really going to be a common place to plug this into :confused:.

I started it out trying to make URI::Params::Serializable to do what I wanted to, but to implement rails like array params and the named tuples it wasn’t possible, mainly because URI::Params does not care about the parameters ordering but I do.

I have a form builder I use with this, what explain the error API in the controller, but I’m not sure to include a formbuilder on this shard is a good idea.

I just tried to make the API simpler and pleasant to read.

2 Likes

This looks great! Thanks a lot @hugopl, I especially like the annotations :heart:

1 Like