mercredi 8 février 2017

How to handle eager loading on REST API

Imagine you have the following resources for example: Users, Posts and Comments (With typical relationship setup in laravel).

When fetching a single Post, you will have the following endpoint

GET /api/posts/1

// Route model binding
public function show(Request $request, Post $post)
{
   return $post;
}

This is fine if I only want the Post object, but in some pages in my application, I also need to load the User and the Comments associated with the Post.

How do you guys handle that kind of scenario?

1. Should I load everything in that endpoint like:

return $post->load(['user', 'comments.user']);

and call it a day? (nope)

2. Should I accept an additional parameter that will tell my controller to load the relationship based on that value?

public function show(Request $request, Post $post)
{
    if ($request->has('rel')) {
        $post->load($request->input('rel'));
    }

     return $post;
}

with this approach I could do something like this:
GET /api/posts/1?rel=user
returns Post with User

or I could build an array of parameter with jquery's $.param(['user', 'comments.user'])

GET /api/posts/1?rel%5B%5D=user&rel%5B%5D=comments.user
returns Post with User + Comments.User

but anyone can easily mess with the 'rel' parameter so I also need to check that ¯\(°_o)/¯

3. Just create a new endpoint for every specific requirements. (what should your endpoint look like for the example above?).


I'm building a SPA with Angular + Laravel (just a self-consumed API) for my Internal Project when I counter this pitfall. The second approach is what I currently using for basic fetching and I use the third approach for more complex requirements

Any inputs are appreciated.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire