lapis icon indicating copy to clipboard operation
lapis copied to clipboard

`true` as a route handler

Open DarkWiiPlayer opened this issue 6 years ago • 4 comments

many of my applications follow the pattern app:get("name", "route", require("pages.name"), and it would be convenient to just pass true as a handler, similar to how render: true works. Adding this feature would be fairly easy, but I first wanted to get some feedback before making a pull request.

-- application.moon
match: (route_name, path, handler) =>
    if handler == nil
      handler = path
      path = route_name
      route_name = nil

    --- I suggest adding this ----------------
    if handler==true
      handler = require "actions.#{route_name}"
    ------------------------------------------

    @ordered_routes or= {}
    key = if route_name
    ...

Who else does this, and would want a similar feature, and who does it in a different (better?) way and doesn't need this? (Note that I am mostly talking about using lapis with lua, though this might be useful with moonscript as well)

DarkWiiPlayer avatar Feb 27 '18 15:02 DarkWiiPlayer

actions instead of pages is probably more appropriate

leafo avatar Feb 28 '18 01:02 leafo

Changed it to actions

DarkWiiPlayer avatar Feb 28 '18 06:02 DarkWiiPlayer

Before filters expect actions to be functions and not booleans, so that code would have to be uploaded. It might make more sense to load the actions when the application is loaded instead of lazily on match (but lazy loading is nice for speeding up reboot of app)

leafo avatar Feb 28 '18 18:02 leafo

Before filters expect actions to be functions and not booleans

by that you mean it expects them to be type(action)=="function" or just that you can call them?

In the second case, one could just use a table with a __call metamethod that lazy-loads the actual function. Maybe that could even be useful in other places.


EDIT: small proof of concept implementation https://gist.github.com/DarkWiiPlayer/6cc47c3f950f029bbf6277039e044e61

This would change the code to

-- application.moon
import lazyfunc from require "lazy"
...
match: (route_name, path, handler) =>
    if handler == nil
      handler = path
      path = route_name
      route_name = nil

    --- I suggest adding this ----------------
    if handler == true
      handler = lazyfunc -> require "actions.#{route_name}"
    --- And while we're at it ----------------
    elseif handler == false
      handler = -> { status: 404, "I'm still working on this page tehe~" }
      -- TODO: redirect to random youtube cat video
    ------------------------------------------

    @ordered_routes or= {}
    key = if route_name
    ...

not really much of a change to be honest xD


As for the speed overhead, it should be negligible for all but the smallest actions and the places where even that difference is important, you'd be using plain resty anyway.

DarkWiiPlayer avatar Mar 25 '18 09:03 DarkWiiPlayer