RestRserve router end point as a module

27 Views Asked by At

TLDR: how to create a router add an end point to it with the logic, and then add it to the RestRserve application. The purpose is to modularise my code. Finally, this would allow me to group my routes and then import that router into app.

I'm looking to do something like this:

  • index.R: app
    • user_data.R: user_data_router (groups routes)
      • user_data_route_1.R
      • user_data_route_2.R

So in index.R I would mount/add a single router, which in turn groups together other routes (by routes I mean end points)

I'm learning RestRserve I didn't find this online nor in the docs. I'm looking to create a router object and add an endpoint to it in a separate file, then export it so I can import from my main.R and add it to my application. The purpose is to modularise my code.

My minimal example:

#!/usr/bin/env Rscript
box::use(RestRserve)

app <- RestRserve$Application$new()

app$add_get("/echo", \(.req, .res) {
    .res$set_body(list(paste0("The message is: '", .req$get_param_query("msg"), "'")))
    .res$set_content_type("application/json")
})


backend <- RestRserve$BackendRserve$new()
backend$start(app, http_port = 8080)

I was hoping in a separate file called echo.R I can do the following (this does not work; pseudocode):

box::use(RestRserve)

echo <- RestRserve$Router$new()

echo$add_get("/echo", \(.req, .res) {
    .res$set_body(list(paste0("The message is: '", .req$get_param_query("msg"), "'")))
    .res$set_content_type("application/json")
})

#' @export
echo <- echo

RestRserve does indeed have a Router class but the documentation is hidden and does not have any methods for adding end points.

If I can do this then I would be able to import into my main.R and use it as such I hope:

box::use(RestRserve)

app <- RestRserve$Application$new()

box::use(./echo[ echo ])

app$mount("/", echo)

backend <- RestRserve$BackendRserve$new()
backend$start(app, http_port = 8080)

I know this can be done using plumber I don't want to use plumber.

0

There are 0 best solutions below