Validating UUID in the URL

313 views
Skip to first unread message

Mateusz Urbanski

unread,
Apr 2, 2021, 4:59:15 PM4/2/21
to Roda
Hi, In my Roda + Sequel application I have a Todo model that have UUID primary key:

In my app.rb I have the following routes:

r.on('todos') do
  # GET api/v1/todos/:uuid
  r.on(String) do |id|
    todo = current_user.todos_dataset.with_pk!(id)

    r.get do
      todo.to_json
    end
  end

  # GET api/v1/todos
  r.get do
    current_user.todos.to_json
  end
end

The problem is that when I visit GET api/v1/todos/invalid-id it raises me:

PG::InvalidTextRepresentation: ERROR:  invalid input syntax for type uuid: "invalid-todo"

How can I fix that?

Thanks in advance.
Mat

Jeremy Evans

unread,
Apr 2, 2021, 6:39:48 PM4/2/21
to ruby...@googlegroups.com
One way would be to use a matcher that only allows valid UUIDs:

r.on 'todos' do
  r.on /(\h{8}(?:-\h{4}){3}-\h{12})/ do |id|
    # ...
  end
  # ...
end

If you are using a similar regexp in multiple places, you may want to use the symbol_matchers plugin:

plugin :symbol_matchers
symbol_matcher :uuid, /(\h{8}(?:-\h{4}){3}-\h{12})/
r.on 'todos' do
  r.on :uuid do |id|
    # ...
  end
  # ...
end

The class_matchers plugin would also work, assuming you have some UUID class in your application that you could use.

Thanks,
Jeremy


Mateusz Urbanski

unread,
Apr 3, 2021, 6:47:20 AM4/3/21
to Roda
Thank you for your help, Jeremy.
The problem is that now when I visit GET api/v1/todos/invalid-todo-id it calls the action for listing all todos in the system GET api/v1/todos

Jeremy Evans

unread,
Apr 3, 2021, 1:41:03 PM4/3/21
to ruby...@googlegroups.com
On Sat, Apr 3, 2021 at 3:47 AM Mateusz Urbanski <mateusz....@htdevelopers.com> wrote:
Thank you for your help, Jeremy.
The problem is that now when I visit GET api/v1/todos/invalid-todo-id it calls the action for listing all todos in the system GET api/v1/todos

You should use "r.get true do" instead of "r.get do" in both cases, to force a terminal match.  The only time you should use "r.get do" is when you have already made a terminal match using something like r.is.

Thanks,
Jeremy
 
--
You received this message because you are subscribed to the Google Groups "Roda" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ruby-roda+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ruby-roda/55c45913-4d51-4c30-92a9-ac235c98b92an%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages