Using multiple filters with programmatic plumber

I have defined a route with two endpoints (randLetters and ping). I then defined two filters (validation and add session ID). I then want the ping endpoint to opt out of the filter validation, but not the session ID filter, so I added a preeempt tag. However, it looks like the order filters are defined matters: the code as provided works as expected, but if I swap around the two filters and I define the validation filter before the session ID one, then ping opts out of both filters.

Anyone knows what is going on? Is it expected that the order of filers declaration matters? Is there some wrong with my code?

library(plumber)

pr() %>%
  # filters
  pr_filter('lettersSessionID', function(req){
    print('filter add session ID')
    forward()
  }) %>%
 pr_filter('lettersValidation', function(req){
    print('filter validation')
    forward()
  }) %>%
  # endpoints
  pr_get(path = '/randLetters',
         handler = function(n = 10){sample(letters, n, replace = TRUE)},
         serializer  = serializer_json()) %>%
  pr_get(path = '/ping',
         preempt = 'lettersValidation',
         handler = function(){},
         serializer = serializer_json()) %>%
  pr_run()

Filters are added to the filters list in order. The filters add order does matter. When you set a preempt, you insert the endpoint execution before the filter of the same name.

For a given filter list, add in order
[a, b, c, d, e]
And an endpoint execution [z]

If you preempt [z] with [d], the execution loop will look like
[a, b, c, z]

[d] and [e] are ignored unless the endpoint returns a plumber::forward().

If you preempt [z] with [a], the execution loop will look like
[z]

There is a special name you can use to jump to the front of queue, setting preempt to __first__. The default is to run all filters before looking for an endpoint, which is preempt = "__no-preempt__".

That makes sense. I knew the order matters, but I thought only in relation to the order they are executed, I did not consider the role of the endpoint in this. Thanks for clarifying.

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.