lundi 1 mai 2017

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?
        }
    });
}
});




Aucun commentaire:

Enregistrer un commentaire