Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added responseModel support #110

Closed
wants to merge 1 commit into from

Conversation

bagilevi
Copy link

Include the entity defined in http_codes as a responseModel.

Example:

desc 'This returns something or an error', {
  entity: Entities::Something,
  http_codes: [
    [200, "OK", Entities::Something],
    [403, "Refused to return something", Entities::Error]
  ]
}

@dblock
Copy link
Member

dblock commented Jul 14, 2014

Merged via tim-vandecasteele@99b1430, thank you. Please check my commit, there were a few changes.

@dblock dblock closed this Jul 14, 2014
@dspaeth-faber
Copy link
Contributor

@bagilevi how can I use this error model in grape?

error!(???, 400)

@dspaeth-faber
Copy link
Contributor

Oh, i did find it. You don't use error!. Maybe it would be great when error! uses the error hash converts it into a openstuct and present it via the presenter.

@bagilevi
Copy link
Author

@dspaeth-faber I define a custom error_formatter which will find an error presenter class based on the error code.

error_formatter :json, ->(message, backtrace, options, env) {
  h = if message.is_a?(String)
        { message: message }
      else
        message
      end
  klass = Iron::Entities::Error
  if h[:code] && (klass_name = h[:code].try(:to_s).try(:classify)) && klass.const_defined?(klass_name)
    klass = klass.const_get(klass_name)
  end
  errobj = klass.represent(Hashie::Mash.new(h))
  JSON.generate(error: errobj)
}
error!({ code: 'deleted', message: "Account has been deleted, please delete your references." }, 410)

@dspaeth-faber
Copy link
Contributor

@bagilevi Thanks! Look's like some thing which should be added to grape-enitity.

@dspaeth-faber
Copy link
Contributor

I did use your example and came up with the following, maybe it is usefull for you too

module API
  module ErrorFormatter
    module_function
    def call(message, backtrace, options = {}, env = nil)
      if message.is_a?(Hash)
        message =  message.dup
        presenter = message.delete(:with)

        if presenter
          message = Hashie::Mash.new(message)
          message = presenter.represent(message, {env: env}).serializable_hash
        end
      end

      Grape::ErrorFormatter::Json.call(message, backtrace, options, env)
    end
  end
end
error!({ code: 'deleted', with: Iron::Entities::Error, message: "Account has been deleted, please delete your references." }, 410)

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.

3 participants