简体   繁体   中英

EmberJS: Throw 404 from route model hook when store query results in empty collection

I have an Ember project (v2.12.0) where I'd like to find a certain model by its slug. These slugs are supposed to be unique.

When I query for a record with Ember.store.query() , however, the returned promise always resolves to a collection by the nature of query() and the JSON API specification.

When the server does not find a record with that particular slug, the response is still 200 OK with an empty collection for my-model[] as its payload.

My question is:

How can I best assert in my ember route's model() hook that the collection contains exactly 1 item, or abort and transition to a 404 route/page otherwise?

This is the code I have so far:

import Ember from 'ember';

export default Ember.Route.extend({

model(params) {

    return this.store.query('my-model', {
        filter: {
            slug: params.myModelSlug
        }
    }).then((modelCollection) => {

        // Code below fails when modelCollection is empty...
        return modelCollection.get('firstObject');

        if (modelCollection.get('length') === 0) {
            // Throw new Ember Error 404?
        }
    });
}
});

Thats nothing you should do in your route! Thats a job for the adapter! Don't forget queryRecord . Thats the method you should call from your route. The rest is much nicer in the adapter.

However, you can do this in the route. The important thing is to know about error substates . Just throw "foo" , or implement your own error object. Next show the 404 message on the error substate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM