有没有办法使用 R Plumber 在 API 中添加可选参数?

有没有办法使用 R Plumber 在 API 中添加可选参数?

问题描述:

我有这个路由,我正在尝试使其工作:

I have this routing that I'm trying to make it work:

#* @get /outcomes-aggregate/<categoryId:int>/<classId>/<perspectiveID>/<sn>
#* @serializer unboxedJSON
function(res, req, categoryId, classId,sn=NULL){
  
  ## initialization
  query <- NULL
  data_to_send <- list()
  ...
}

这个 api 应该接受带有可选 sn 值的请求.但是,这是行不通的.sn 值可能存在也可能不存在,并且基于该值运行查询.但是当我运行它时,我不断收到此错误:

This api is supposed to take the request with optional sn value. However, this is not working. The sn value may or may not exist and the query is ran based on this value. But when I run it, I keep getting this error:

call: http://localhost:3982/outcomes-aggregated/1/342342

0   "404 - Resource Not Found"

它只有在我还包含 sn 时才有效.

It only works if I also include the sn.

call: http://localhost:3982/outcomes-aggregated/1/342342/NULL

我怎样才能使这个参数成为可选的?还是我必须创建另一个没有这个值的函数?

How can I make this parameter optional? Or will I have to create another function without this value?

更新

我更新了路由和逻辑以尝试更正此问题.

I updated the routing and the logic to attempt to correct for this issue.

#* @get /outcomes-aggregate/<categoryId:int>/<classId>/<sn>
#* @serializer unboxedJSON
function(res, req, categoryId, classId,sn=NULL){
  
  ## initialization
  query <- NULL
  data_to_send <- list()
  ...

   if(missing(sn) || pracma::strcmp(sn, "NULL")){
    query <- paste0("SELECT * FROM classes WHERE classID = '", classId, "'")
  } else{
    query <- paste0("SELECT * FROM classes WHERE classID = '", classId, "' and sn = '", sn , "'")
  }
  ...

}

这暂时有效,但我仍然必须在 url 中添加 NULL.我很想听听一个更好的方法来做到这一点.

This is working for now but I have to still add NULL in the url. I'd love to hear a better way to do this.

根据@BrunoTremblay 的回复,我最终将函数转换为使用查询而不是路径.这工作得很好.

Base on @BrunoTremblay's response, I ended up converting function to use query instead of path. This worked fine.

新函数如下所示:

#* @get /outcomes-aggregate <-- remove the path
#* @serializer unboxedJSON
function(res, req, categoryId, classId,sn=NULL){
  
  ## initialization
  query <- NULL
  data_to_send <- list()
  ...
}