Search code examples
herokuember.jsember-data

Unsure how to retrieve data from a custom endpoint?


Context to this post is I'm a java developer attempting to teach myself Ember. It isn't going well. I realize this question is pretty vague so I apologize, I'm not even sure what I should be asking...

I need to pull data into a model, i.e. via some sort of query, from a heroku json endpoint. In the application.js file, I have the following:

import DS from ‘ember-data’;

export default DS.JSONAPIAdapter.extend({
    host: 'https://cag-brain.herokuapp.com'
});

Ideally I would like to pull this data into a user model, then display that data on a page as a sort of proof of concept. This unfortunately gets me nothing. Nor am I even sure I'm going about this correctly. Should I be doing something different than attempting to use Host Customization? Any guidance would be much appreciated!


Solution

  • There are different things involved for retrieving records via ember-data.

    First of all you should define your models:

    // app/models/post.js
    
    import DS from 'ember-data';
    
    export default DS.Model.extend({
      title: DS.attr('string')
    });
    

    You should retrieve records in a model hook of a route.

    // app\routes\posts.js
    
    import Route from '@ember/routing/route';
    
    export default Route.extend({
      model() {
        return this.get('store').findAll('post');
      }
    });
    

    Then you should configure your api host and maybe a namespace. You included that step in your question:

    // app/adapters/application.js
    
    import DS from ‘ember-data’;
    
    export default DS.JSONAPIAdapter.extend({
        host: 'https://cag-brain.herokuapp.com'
    });
    

    If your api does not implement JSON Api specification you need to customize your serializer and adapter. Ember-data ships with a RESTAdapter/RestSerializer additionally to the default adapter and serializer which implements JSON Api spec. There is also one abstract adapter and serializer If you need to start from scratch. Before that I would definitely have a look if there is any community adapter/serializer fitting your needs.

    To decouple api and client development and to speed up tests I would recommend ember-cli-mirage which allows you to mock your api.