ambiorix icon indicating copy to clipboard operation
ambiorix copied to clipboard

refactor http methods in Routing?

Open kennedymwavu opened this issue 9 months ago • 0 comments

we have a lot of duplication when defining http methods; they're all similar, the only difference being the method itself.

see:

  • https://github.com/ambiorix-web/ambiorix/blob/ad6c3bff42d38b9b806415e2fffb52c1b9426b07/R/routing.R#L40
  • https://github.com/ambiorix-web/ambiorix/blob/ad6c3bff42d38b9b806415e2fffb52c1b9426b07/R/routing.R#L64
  • https://github.com/ambiorix-web/ambiorix/blob/ad6c3bff42d38b9b806415e2fffb52c1b9426b07/R/routing.R#L88
  • https://github.com/ambiorix-web/ambiorix/blob/ad6c3bff42d38b9b806415e2fffb52c1b9426b07/R/routing.R#L112
  • https://github.com/ambiorix-web/ambiorix/blob/ad6c3bff42d38b9b806415e2fffb52c1b9426b07/R/routing.R#L136
  • https://github.com/ambiorix-web/ambiorix/blob/ad6c3bff42d38b9b806415e2fffb52c1b9426b07/R/routing.R#L160
  • https://github.com/ambiorix-web/ambiorix/blob/ad6c3bff42d38b9b806415e2fffb52c1b9426b07/R/routing.R#L184

i was wondering whether it'd be a good idea to refactor all this to:

Routing <- R6::R6Class(
  "Routing",
  public = list(
    error = NULL,
    get = NULL,
    put = NULL,
    patch = NULL,
    delete = NULL,
    post = NULL,
    options = NULL,
    all = NULL,
    #' @details Initialise
    #' @param path Prefix path.
    initialize = function(path = "") {
      private$.basepath <- path
      private$.is_router <- path != ""
      self$add_http_methods()
    },
    add_http_methods = function() {
      methods <- c("get", "put", "patch", "delete", "post", "options", "all")

      for (i in seq_along(methods)) {
        value <- methods[i]

        method <- value
        if (identical(value, "all")) {
          method <- methods[methods != "all"]
        }
        method <- toupper(method)

        self[[value]] <- function(path, handler, error = NULL) {
          assert_that(valid_path(path))
          assert_that(not_missing(handler))
          assert_that(is_handler(handler))

          r <- list(
            route = Route$new(private$.make_path(path)), 
            path = path, 
            fun = handler, 
            method = method,
            error = error %error% self$error
          )
          private$.routes <- append(private$.routes, list(r))

          invisible(self)
        }
      }

      invisible(self)
    },
  # ...

kennedymwavu avatar Mar 16 '25 08:03 kennedymwavu