Skip to content

Instantly share code, notes, and snippets.

@SarathSantoshDamaraju
Created September 20, 2019 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SarathSantoshDamaraju/31425b7b805b7b3c866188ac51e1f2a9 to your computer and use it in GitHub Desktop.
Save SarathSantoshDamaraju/31425b7b805b7b3c866188ac51e1f2a9 to your computer and use it in GitHub Desktop.
Ember relationships with [github API]
/*
Using ember relation ships with API similar to github
Adpater: RESTAdapter
Serialiser: JSONSerializer
*/
/*
Create a parent model
*/
// models/user.js
import DS from 'ember-data';
const { Model, attr, hasMany } = DS;
export default Model.extend({
name: attr('string'),
company: attr('string'),
location: attr('string'),
email: attr('string'),
repos: hasMany('repo') // user has 1-to-many relation with repo
});
/*
Create a Relation
*/
// models/repo.js
import DS from 'ember-data';
const { Model, attr, belongsTo } = DS;
export default Model.extend({
name: attr(),
url: attr(),
language: attr(),
user: belongsTo('user')
});
/*
Adapters
*/
import DS from 'ember-data';
import { computed } from '@ember/object';
export default DS.RESTAdapter.extend({
host: 'https://api.github.com',
headers : {
Authorization: "token /*[key_here]*/" // replace!
}
});
/*
Serializers
*/
// serializers/application.js
import DS from 'ember-data';
import { decamelize } from '@ember/string';
export default class ApplicationSerializer extends DS.JSONSerializer {
keyForAttribute(key) {
return decamelize(key);
}
}
// serializers/user.js
import DS from 'ember-data';
import ApplicationSerializer from './application';
export default ApplicationSerializer.extend ({
primaryKey: 'login',
normalizeFindRecordResponse(store, type, payload) {
payload.links = {
repos: payload.repos_url
// ... can load other relations here
}
return this._super(...arguments);
},
});
/*
Reference the data : Related data will not be loaded unless this.
*/
<ul>
{{#each data.repos as |repo|}}
<li>
{{repo.url}}
</li>
{{/each}}
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment