Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get a nested resource without getting the parent? #13

Closed
Dylan-Chapman opened this issue Jun 4, 2018 · 6 comments
Closed

How to get a nested resource without getting the parent? #13

Dylan-Chapman opened this issue Jun 4, 2018 · 6 comments
Labels
enhancement New feature or request

Comments

@Dylan-Chapman
Copy link

Say I want to get the posts for ID user 1, "/users/1/posts". However, I have no need to get the actual user object, "/users/1" first. Is there a built-in way to do this? I didn't have luck trying to run User.find(1).posts().get() for example. Any other way to accomplish this without the unneeded API call?

@robsontenorio
Copy link
Owner

robsontenorio commented Jun 4, 2018

You can create new instances manually. See on README.

let post = new Post()
post.id = 123

// or just pass as a payload

let post = new Post({id: 123})

// of course you can pass any other params

Then..

// GET /posts/123/comments
let comments = await post.comments().get()

Make sure Post and Comment extends from a BaseModel.

@Dylan-Chapman
Copy link
Author

Awesome, thanks! This method seems to work with get but not find as far as I can tell, though? So, modeling off of your example, I have:

const User = new User({id: 1})
const Post = await User.posts().find(2)

This fires "/posts/2" instead of "/users/1/posts/2".

@robsontenorio
Copy link
Owner

The find() method is suposed to be used with single resources.

For nested resources you should always use get().

As described on README you can use another methods before get() on nested resources.

await user.posts().where('id', 2).get()

@Dylan-Chapman
Copy link
Author

Okie dok. Is there some philosophy behind the find() method not being able to be used with nested resources? I thought nested resources with multiple identifiers was a common REST API pattern?

@robsontenorio
Copy link
Owner

robsontenorio commented Jun 4, 2018 via email

@robsontenorio robsontenorio added the enhancement New feature or request label Jul 22, 2018
robsontenorio added a commit that referenced this issue Jul 26, 2018
Find method respects relationships, fixes #13
@robsontenorio
Copy link
Owner

@Dylan-Chapman Now you can do this

const User = new User({id: 1})
const Post = await User.posts().find(2)

Just upgrade to 1.1.0. Thanks @vjoao for PR!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants