pragma icon indicating copy to clipboard operation
pragma copied to clipboard

Resource definition DSL

Open aldesantis opened this issue 7 years ago • 0 comments

Rather than requiring users to write/generate boilerplate code for each resource, it shouldn't be too hard to allow users to define resources with a DSL and provide hooks for customization, e.g.

# app/resources/api/v1/post.rb
Pragma::Resource.define :post do |config| # entire block is optional
  config.model_class = ::Post # optional, computed by default

  config.attributes do |attributes|
    attributes.define :title, :body do
      type :string
      validate :required?
    end

    attributes.define :author do
      default ->(options) { options['current_user'] }
      validate :required?
      visible false # not exposed in decorator
    end

    attributes.define :send_newsletter do
      type :boolean
      only :create # cannot be updated
      virtual # not saved to model
    end
  end

  # These would accept any callable object which receives `options`.
  # We would also have before_* and around_* hooks.
  config.hooks do |hooks|
    hooks.after_create API::V1::Post::Hook::NotifySubscribers
    hooks.after_update API::V1::Post::Hook::TouchLastUpdate
    hooks.after_save API::V1::Post::Hook::GenerateSummary
    hooks.after_destroy API::V1::Post::Hook::RemoveFromFeed
  end

  config.policy do |policy|
    policy.on :create? do |user, post|
      # ...
    end
  end
end

We should still support custom resources defined the old way.

This would probably be a separate library/gem (Pragma::Resource?) providing a catch-all API endpoint that looks at the configuration and executes the appropriate logic.

aldesantis avatar Jul 22 '18 17:07 aldesantis