Best Practices for Web Service Design with Ember Data

Based on what I’ve done at work:

  1. Most of our client-side models are simplified versions of the server-side models. In some cases the server flattens several tables into one abstraction which it serves to the client. This seems reasonable to me, as the client should only see what it needs.

  2. We have a few places where we serve models that are best identified using composite keys, but we present the model through the REST API using a primary key that concatenates the primary key values with a hyphen. Ember Data and the JSON API are suited to requesting/updating/deleting records using a single ID, which can be a string.

  3. Ember Data doesn’t automatically purge cached models. Whenever the user navigates away from a route (see the Route’s deactivate hook) where lots of data may have been cached, which is no longer needed, I purge those records from the cache. Specifically I filter over all the items of a type for just those that are not referenced by any other models in the cache. Don’t want to break dependencies. Use the store.unloadRecord method, and be sure to rollback first if the models may be dirty.

  4. Dependent records (belongsTo or hasMany) will be requested immediately after Ember Data gets a model referencing records not in the store. You can sideload the records that will be needed, by adding additional top-level fields in the JSON payload response, and Ember will add them to the store so they won’t be requested separately, e.g. responding to find('person')

{
	people: [
		{id: 1, user: 101, ...},
		{id: 2, user: 102, ...}
	],
	users: [
		{id: 101, ...},
		{id: 102, ...}
	]
}

Hope someone else chimes in, as I’m sure there are other ways, but we’re comfortable with the approach we chose.

3 Likes