jsonapi-serializable icon indicating copy to clipboard operation
jsonapi-serializable copied to clipboard

Validate presence of a class in the `class` argument

Open thec0keman opened this issue 6 years ago • 3 comments

When rendering custom class / serializer mappings:

render_jsonapi records, class: {
  :'User' => ::FrontEnd::SerializableUser,
  :'Comment' => ::FrontEnd::OnDemand::SerializableComment
}

If the left-hand key isn't correct, you will get a cryptic error

undefined method `new' for nil:NilClass

I think a solution would be to update _build in renderer to something like:

def _build(object, exposures, klass)
  raise "#{ object.class.name.to_sym } not found in the class option passed to jsonapi_render" if klass[object.class.name.to_sym].blank?

  klass[object.class.name.to_sym].new(exposures.merge(object: object))
end

This way, if you've forgotten to map something there will be a helpful error message.

thec0keman avatar Dec 13 '18 22:12 thec0keman

I agree that the error message is not very helpful. However, checking for blank? is not enough, as it would still allow non-existing classes. Probably something along the lines of raise ... unless klass[...].is_a? JSONAPI::Serializable::Resource. @dawidof What do you think?

beauby avatar Apr 05 '19 16:04 beauby

I think its a good idea. I' also spent some time in past to figure out from where this error is coming.

dawidof avatar Apr 05 '19 17:04 dawidof

Looks like this was resolved by https://github.com/jsonapi-rb/jsonapi-serializable/commit/914ccdecef9ec8b6f7ebca96bada5825fe99408f

tlconnor avatar Apr 09 '19 23:04 tlconnor