codenoble / cache-crispies

Speedy Rails JSON serialization with built-in caching
MIT License
156 stars 16 forks source link

Provide option to disable root key #46

Closed mithucste30 closed 1 year ago

mithucste30 commented 2 years ago

I have a legacy application where existing client excpect a single or array of flat object like this

{
  "id": "xxx",
  "title": "xxx"
}
[
  {
    "id": "xxx",
    "title": "xxx"
  },
  {
    "id": "xxx",
    "title": "xxx"
  }
]

How to achieve this here?

Flixt commented 1 year ago

I think it is possible to achieve this by setting the collection_key for the serializer to nil.

class MySerializer < CacheCrispies::Base
    collection_key nil
    serialize :id
    serialize :title
end

Although this would only make sense if you use the cache_render helper for your controller, so you can benefit from the cached plan.

class MyController < ApplicationController
  def index
    cache_render MySerializer, MyRecord.all
  end
end

If you just want to serialize to json you could also use the CacheCrispies::Collection yourself

class MySerializer < CacheCrispies::Base
    serialize :id
    serialize :title
end

arr = [OpenStruct.new(id: 1, title: "Title 1"), OpenStruct.new(id: 2, title: "Title 2")]
CacheCrispies::Collection.new(arr, MySerializer, {}).as_json

# => [{:id=>1, :title=>"Title 1"}, {:id=>2, :title=>"Title 2"}]

Have a look at the implementation of cache_render to see what is possible: https://github.com/codenoble/cache-crispies/blob/9b6c09286313dca04caf2670ca86d4e4b2f8fa54/lib/cache_crispies/controller.rb#L30

adamcrown commented 1 year ago

Thanks @Flixt . That seems accurate to me. It may not be initially obvious. But it should be totally doable with what is already built into the gem.

I'm going to close this issue.