fast_jsonapi icon indicating copy to clipboard operation
fast_jsonapi copied to clipboard

Don't serialize meta if empty

Open remear opened this issue 5 years ago • 2 comments

When defining some per-resource meta

meta do |o|
end

if it evaluates to nil, "meta":null is still serialized. Is there a way to not serialize meta in this case?

remear avatar May 03 '19 14:05 remear

Probably subjective, but I think "meta": null is a reasonable output for this case. It sounds like what you want is a conditional meta field, like:

  • https://github.com/Netflix/fast_jsonapi#conditional-attributes

There's also a feature request open for this behavior on links: https://github.com/Netflix/fast_jsonapi/issues/346

dpikt avatar May 20 '19 19:05 dpikt

I agree, unless there is a huge performance hit, the ability to conditionally serialize meta is good.

But because meta is not one single unit like an attribute or a link, it may be hard to simply apply a conditional Proc unless we allow multiple calls to meta and combine the results.

An easier option is to just:

  • return an empty hash if you want to serialize something
  • don't serialize meta if the block returns nil

Or something like:

meta serialize_nil: false do |record, params|
  if condition
    {
      key: "value"
    }
  end
end

where the default value is serialize_nil: true to keep compatibility.

leehericks avatar Feb 20 '20 01:02 leehericks