open kadamwhite/wordpress-rest-api#127

Determine how to handle embedded responses

kadamwhite

When you make a request like wp.posts().id( 42 ).embed(), the returned JSON object will exactly mirror the API response you would get in the browser: that is to say, the response object will have an ._embedded: {} object containing arrays of the embedded versions of linked author, media, and taxonomy term, etc resources.

There are two (and a half) ways we could proceed:

1: Leave _embedded the way it is, do not mutate the response object in any way

2: Mutate the response object to in-line the contents of _embedded into the response, so that e.g. instead of

{
  // ...
  author: 3,
  _embedded: {
    author: [ {
      id: 3,
      name: 'Muscles McTouchdown',
      // ...
    }]
  }
}

you would get simply

{
  // ...
  author: {
    id: 3,
    name: 'Muscles McTouchdown',
    // ...
  }
}

This has the advantage of "shielding" the user from the nuances of embedded data, and they can easily determine whether they've got embedded data or not by e.g. inspecting the typeof post.author. That could be considered a downside as well.

2.5: Implement some standardized way of defining post transformations, and make this configurable. I'm not 100% sure I'm comfortable heading down that road yet (it was previously discussed and back-burnered way back in #5) but it would allow users to pick their own poison, at the expense of increasing library complexity.

Opinions welcome!

kadamwhite

cc @tkellen as I know you in particular have talked through these questions with regard to JSON API: WP-API doesn't conform to that standard but I'm curious how you all handled embedding.

artoliukkonen

I'd personally like 2 the most, since this is the way many other similar APIs work (Facebook, Contentful, etc).

kadamwhite

After discussion with @artoliukkonen, @nb, @adamsilverstein & others at the Day of REST hack day, this is the proposed implementation:

Within WPRequest, specifically the returnBody method, pass the response body (if object) or response collection members (if array) through a transformation function (defaults to identity function). Provide an interface to specify a function to use at this step. Provide a method that could be used to inline values as described in 2, above, as an opt-in response customization.

tkellen

@kadamwhite There must be an existing client library that can do this transformation for you? If there isn't, I would consider writing one completely separate from this lib. Based on my understanding of the purpose of this library I would not expect it to do anything but pass API results back to me unchanged.

If you're concerned about making things more usable I would solve that problem by providing examples of how to use this other (potentially as-yet-to-be-created) client library to manage that sort of thing.