Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Representors

JSON/NodeJS edition...

Item

{
  "Representer": {
    "Item": {
      "rel": "https://exventure.org/rels/order",
      "href": "https://api.example.org/orders/1",
      "item": {
        "Order": {
          "id": "10",
          "first_name": "User",
          "last_name": "Example"
        }
      },
      "links": [
        {
          "Link": {
            "rel": "self",
            "href": "https://api.example.org/orders/1"
          }
        }
      ]
    }
  }
}

Collection

{
  "Representer": {
    "Collection": {
      "href": "https://api.example.org/orders",
      "name": "orders",
      "items": [
        {
          "Order": {
            "id": 10,
            "first_name": "User",
            "last_name": "Example"
          }
        }
      ],
      "links": [
        {
          "Link": {
            "rel": "self",
            "href": "http://api.example.org/orders"
          }
        },
        {
          "Link": {
            "rel": "up",
            "href": "http://api.example.org/orders?up"
          }
        }
      ]
    }
  }
}

Representers

Starting data

order = %Order{
  id: 10,
  first_name: "User",
  last_name: "Example",
}

orders = [order]

# Render function for an order
def render("order.json", %{order: order}) do
  Map.take(order, [:id, :first_name, :last_name])
end

Item

%Representer.Item{
  rel: "https://exventure.org/rels/order",
  href: RouteHelpers.order_url(Endpoint, :show, order.id),
  item: render("order.json", %{order: order}),
  links: [
    %Representer.Link{
      rel: "self",
      href: RouteHelpers.order_url(Endpoint, :show, order.id)
    },
  ],
}

Collection

%Representer.Collection{
  href: RouteHelpers.order_url(Endpoint, :index),
  name: "orders",
  items: Enum.map(orders, &item/1),
  links: [
    %Representer.Link{
      rel: "self",
      href: RouteHelpers.order_url(Endpoint, :index)
    },
    %Representer.Link{
      rel: "up",
      href: RouteHelpers.root_url(Endpoint, :index)
    }
  ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment