Override buildURL method to include parent model's id

≡放荡痞女 提交于 2019-12-06 01:45:22

问题


Regarding ember-data and subclassing DS.RESTAdapter to override buildURL.

I have two endpoints. Lets say they are:

example.com/users/user-id
example.com/users/user-id/images

Replace "user-id" with the actual user id.

So I have two models:

App.User = DS.Model.extend
    images: DS.hasMany 'image',
        async: true
        inverse: 'user'

App.Image = DS.Model.extend
    user: DS.belongsTo 'user',
        async: true
        inverse: 'images'

However, the payload from /users/user-id endpoints do not return the image ids. I do not have control over this (it's a third party api).

Therefore I need to make a separate request to /users/user-id/images. I'm subclassing DS.RESTAdapter in order to specify the url:

App.ImageAdapter = DS.RESTAdapter.extend
    buildURL: (type, id) ->
        # need to return "/users/user-id/images"
        # but need to get the value of user-id somehow

From the route, how would I even go about passing in the user id to the store so that it can call the buildURL method in the custom adapter with the user id?

App.UserRoute = Em.Route.extend
    afterModel: (model) ->
        # how to provide value of `model.get 'id'` to store/adapter/buildURL?
        # do I even do that here?
        promise = @get('store').find 'image'
        @controllerFor('images').set 'model', promise

I guess I can provide a hash to find and skip buildURL altogether. But findQuery is a private method. Is there a more preferred way to do this?

App.UserRoute = Em.Route.extend
    afterModel: (model) ->
        promise = @get('store').find 'image', userId: model.get 'id'
        @controllerFor('images').set 'model', promise

App.ImageAdapter = DS.RESTAdapter.extend
    findQuery: (store, type, query) ->
        imagesURL = "#{@host}/users/#{query.userId}/images"
        delete query.userId
        @ajax(imageURL, 'GET', { data: query });

回答1:


There is definitely nothing wrong with overriding findQuery, that's part of the fun of being able to extend the adapters. We've had to do the same thing (our rest endpoints are really exciting).



来源:https://stackoverflow.com/questions/21964155/override-buildurl-method-to-include-parent-models-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!