javascriptjsdata

How can you create a nested, custom class-action on a JS-Data resource?


I have a JS-Data object which is nested (i.e. has a parent relation)

(NB all code is coffeescript)

Follow = DS.defineResource
  name: "follow"
  endpoint: "follows"
  relations:
    belongsTo:
      post:
        localField: "post"
        localKey: "post_id"
        parent: true
  actions:
    currentUsersFollow:
      method: "GET"
      pathname: "current_users_follow"

I need to call the custom action, currentUsersFollow however I don't want to call it on an instance of Follow. It's a class method like /index and has no associated instance. However the path still needs to be nested in the parent object.

i.e.

Follow.currentUsersFollow({post_id: 213423})
# => http://ourapp.com/api/v1/follows/current_users_follow 
#
# I would like this to generate:
# http://ourapp.com/api/v1/posts/213423/follows/current_users_follow 
#
# i.e. it's missing the nesting: /posts/213423

This is possible with .findAll

Now if you did this with .findAll() then it will generate the nested route as long as you pass the relevant parent id:

Follow.findAll({post_id: 213423})
# => http://ourapp.com/api/posts/213423/follows

As you can see the post is correctly specified and it goes to the generic endpoint.

How can you create a custom nested action without an instance?

So in short, I would like to create a custom action for my JS-Data resource which is nested within a parent but is not being called on an instance of the child.

Is this possible?


Solution

  • Define your action:

    actions: {
      currentUsersFollow: {
        method: 'GET',
        endpoint: 'posts',
        pathname: 'current_users_follow'
      }
    }
    

    Then call it like this:

    Follow.currentUsersFollow(213423)
    

    and it should produce

    GET /posts/213423/current_users_follow