Skip to content

Allow custom constraints on UUID resource routes generated by jsonapi_resources#662

Merged
lgebhardt merged 1 commit intoJSONAPI-Resources:masterfrom
kenzai:allow-custom-constraints-on-routes
Apr 29, 2016
Merged

Allow custom constraints on UUID resource routes generated by jsonapi_resources#662
lgebhardt merged 1 commit intoJSONAPI-Resources:masterfrom
kenzai:allow-custom-constraints-on-routes

Conversation

@davidstosik
Copy link
Copy Markdown
Contributor

What?

At the moment, the routing method jsonapi_resources completely overrides
options[:constraints] if the resource's resource_key_type is :uuid.
This makes it impossible to define advanced custom constraints that would apply
to those routes, be them related to the :id param or not.

How?

I'm suggesting here to set options[:constraints][:id] in the only case that
no custom constraint was specified on :id. This allows to set a custom
constraint on :id (see below why), as well as others (such as :ip).

Why?

My personal reason to request this feature is to allow myself a way to define
shortcut API endpoints such as /api/users/me, where me will stand for the
current user's UUID. This is actually already possible when ids are numeric
(because options[:constraints] is not overridden).

Example

#config/routes.rb
jsonapi_resources :users, constraints: {id: /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|me/}

#app/controllers/application_controller.rb
class ApplicationController < JSONAPI::ResourceController
  before_action :_load_me, only: %w(get_related_resource get_related_resources)

  def _load_me key = "user_id"
    return unless current_user && params[key] == "me"
    params[key] = current_user.id
  end
end

#app/controllers/users_controller.rb
class UsersController < ApplicationController
  before_action :_load_me, except: %w(index create)

  def _load_me
    super("id")
  end
end

@lgebhardt lgebhardt merged commit d4880fe into JSONAPI-Resources:master Apr 29, 2016
@lgebhardt
Copy link
Copy Markdown
Contributor

@davidstosik Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants