Custom Adapter to support RocketPant with Rails

76 Views Asked by At

I am using rocket_pants gem to build backend API https://github.com/Sutto/rocket_pants

It have a specific format to output data:

{ 
    "response":[
        {"id":1,"title":"Object Title","description":"Object Description"},
        {"id":1,"title":"Object Title","description":"Object Description"} ],
    "count":2,
    "pagination": {
          "previous":null,
           "next":null,
           "current":1,
           "per_page":30,
           "count":2,
           "pages":1}
}

I am using Batman.RailsStorage to persist models. But actions like MyApp.Model.get('all') works fine on the backend but they actually do not parse and load model objects.

Can you guide me how to configure StorageAdapter or write new one to handle such kind of data format?

2

There are 2 best solutions below

0
On BEST ANSWER

You could try overriding the collectionJsonNamespace method (defined on Batman.RestStorage).

I see that it's used after a readAll operation to get records from the HTTP response.

For example:

class MyApp.RocketPantsStorage extends Batman.RailsStorage
   collectionJsonNamespace: -> "response"

Then in your model

#= require ../rocket_pants_storage
# the storage adapter must be available at load time
class MyApp.SomeModel 
   @persist MyApp.RocketPantsStorage

Does that work?

0
On

With the same approach mentioned in answer from @rmosolgo I build paginator as well.

class MyApp.RocketPantsPaginator extends Batman.ModelPaginator
  totalCountKey: "pagination.count"

  loadItemsForOffsetAndLimit: (offset, limit) ->
    params = @paramsForOffsetAndLimit(offset, limit)
    params[k] = v for k,v of @params
    @model.load params, (err, records, env) =>
      if err?
        @markAsFinishedLoading()
        @fire('error', err)
      else
        response = new Batman.Object(env.response)
        @set('totalCount', response.get(@totalCountKey));
        @updateCache(@offsetFromParams(params), @limitFromParams(params), records)