Ember.JS Tutorial "Super-Rentals" and API Paths

Viewed 56

I've been following the SuperRentals Ember.JS tutorial and have also cloned the finished product from here.

I'm struggling to identify where we define that we retrieve data from rentals.json in <app_dir>/public/api:

XXX@XXXX-XX:~/super-rentals/public/api$ ls
rentals rentals.json

If I change rentals.json to another name, the site stops loading entirely implying some configuration or code requires changing to reflect this.

However, when I grep for "rentals" recursively in <app_dir>/app none of the references returned appear related.

Is this naming picked up by convention, or is it explicitly defined somewhere in the application?

1 Answers

Per the Ember CLI docs:

public/ – This directory will be copied verbatim into the root of the built application. Use this for assets that don’t have a build step, such as images or fonts

Normally in an Ember app, we use this to provide static assets like images or fonts, as the docs indicate. However, in this case, we're taking advantage of the fact that the JSON file used for the tutorial is static. When Ember CLI builds your app, it copies public/api/rentals.json into dist/api/rentals.json. (You can customize where the build output goes, but by default it's dist.)

Then, when any web server serves the files in dist, they're available to request from the server. The Ember dev server is serving all the files from /dist, including the Ember app itself, but also including dist/api/rentals.json, which means you can do fetch('/api/rentals.json') and get that blob of data back.

Ember Data also has niceties that allow you to take that fetch and turn it into something which looks a bit more like an ORM: you can define a model which maps to the API resources. (This works most easily if you're using JSON:API, but with the flexibility to support most REST or REST-ish APIs if you need). Once you define those, you ask for them by the name corresponding to the model, using Ember's conventional layout. In the tutorial, this ends up defining a rental model to go along with the rentals "API endpoint". Combined with the Ember Data store service, instead of writing fetch('/api/rentals.json'), you write this.store.findAll('rental').

If Ember Data isn't the right fit for your back end, you can of course keep using fetch directly, or drop in Axios as a customizable layer on top of fetch, or use a GraphQL client, etc. – the tutorial shows Ember Data as a good "out of the box" option, but it is not at all required for Ember.

Related