digitalocean / kartograph

Kartograph makes it easy to generate and convert JSON. It's intention is to be used for API clients.
MIT License
152 stars 39 forks source link

Allow multiple root keys or nested data (not necessarily nested models) #21

Open danvideo opened 7 years ago

danvideo commented 7 years ago

Maybe there's a better way to handle this, but right now it seems a root key that's multiple levels down is inaccessible. See this example json:

{
  "code": 0,
  "message": "success",
  "data": {
    "monitors": [{
      "name": "TYPE_ONE",
      "status": 1
    },{
      "name": "TYPE_TWO",
      "status": 1
    }],
    "monitor_groups": [{
      "status": 1,
      "monitors": [{
        "name": "DIFFERENT_TYPE",
        "status": 1
      }]
    }]
  }
}

For example if the values after doc["data"]["monitors"] are required (e.g. an array of TYPE_ONE and TYPE_TWO objects) this statement won't find the correct key
root_key plural: "monitors", singular: "monitors", scopes: [:read] The ability to set another level of root keys such as the following would be great: root_key_1 plural: "data", singular: "data", scopes: [:read] root_key_2 plural: "monitors", singular: "monitor", scopes: [:read] Alternatively to have the root key be able to start multiple levels into the json (although then there might be problems with similarly named keys)

driv3r commented 7 years ago

you can have a separate mapping class for monitors, and you can wrap the response within separate one depending on your business logic, i.e.

class Data
  attr_accessor :monitors, :monitor_groups
end

class Monitor
  attr_accessor :name, :status
end

class MonitorGroup
  attr_accessor :status, :monitors
end

class MonitorMapping
  include Kartograph::DSL

  kartograp do
    root_key singular: "monitor", plural: "monitors", scopes: [:read]
    mapping Monitor
    property "name", scopes: [:read]
    property "status", scopes: [:read]
  end
end

class ScreensMapping # ofc. you should pick better name ;)
  include Kartograph::DSL

  kartograp do
    root_key singular: "data", plural: "data", scopes: [:read]
    mapping Data
    property :monitors, plural: true, include: MonitorMapping

    property :monitor_groups, plural: true, scopes: [:read] do
      mapping MonitorGroup
      property :status, scopes: [:read]
      property :monitors, plural: true, scopes: [:read], include: MonitorMapping
    end
  end
end