Search code examples
ember.jsember-data

Recognize the kind of retrieve-record-object in Ember


I am building a crud-route-mixin where I define default functions and actions for routes.

One of the functions has as argument a query object; within the action I perform the call:

_doSomething(query) {
    query.then( result => {
        //do something default with this result
    })
}

The routes call the _doSomething function with different kind of methods. For example:

Route A

export default Ember.Route.extend(CrudRoute, {
    setupController() {
        this._super(...arguments);
        this._doSomething(this.get('store').findAll('paper'));
    }      
}

Route B

export default Ember.Route.extend(CrudRoute, {
    setupController() {
        this._super(...arguments);
        this._doSomething(this.get('store').findRecord('blog-post'));
    }      
}

I was wondering, is it possible to retrieve the method name or type of the query object? So I could do something like this (pseudo code):

_doSomething(query) {
    query.then( result => {
        if (query.getRetrieveMethodName() === 'findAll') {
            //do something default with this array result
        } else if (query.getRetrieveMethodName() === 'findRecord') {
            //do something default with this single record result
        }
    })
}

P.S. Check if the payload is a single record or array is not an option, because I need this distiction in the error handling as well.


Solution

  • Query object returned from findRecord or findAll or query is either PromiseObject or PromiseArray (if you use ember-data). So you can check it type like this (even in case of error):

    import DS from 'ember-data';
    
    _doSomething(query) {
        if (query instanceof DS.PromiseObject) {
           // single result
        }
        else if (query instanceof DS.PromiseArray) {
           // array 
        }
        else {
           throw new Error('Expected ember-data proxy object');
        }
        // Do something useful
     }
    

    But would not it be more simple to provide required data to the controller?

    _doSomething(query, modelName, isArray) {
       query.then( result => {
          //do something default with this result
       });
    }
    
    export default Ember.Route.extend(CrudRoute, {
       setupController() {
          this._super(...arguments);
          this._doSomething(this.get('store').findRecord('blog-post'), 'blog-post', false);
       }      
    

    }