Skip to content

Instantly share code, notes, and snippets.

@runspired
Last active February 16, 2024 06:49
Show Gist options
  • Save runspired/b277df783d5d7d9831c70f9ffb25e131 to your computer and use it in GitHub Desktop.
Save runspired/b277df783d5d7d9831c70f9ffb25e131 to your computer and use it in GitHub Desktop.
Data Integrity Issue Repo
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
/*
{
data: {
type: 'user',
id: '1',
attributes: {
name: 'Chris',
},
relationships: {
bestFriend: { data: { type: 'user', id: '2' } }
}
},
included: [
{
type: 'user',
id: '2',
attributes: { name: 'Joao' }
}
]
}
*/
function normalizeData(raw) {
const data = {};
const included = [
{
type: 'user',
id: '2',
attributes: { name: 'Joao' }
},
{
type: 'user',
id: '3',
attributes: { name: 'James' }
}
];
const resource = data;
resource.type = 'user';
resource.id = String(data.id);
const rawPrimaryRecord = raw.users[0];
resource.attributes = rawPrimaryRecord;
resource.relationships = {
bestFriend: { data: { type: 'user', id: String(rawPrimaryRecord.bestFriendId) } }
};
return { data, included };
}
export default class ApplicationController extends Controller {
@service store;
appName = 'Ember Twiddle';
constructor() {
super(...arguments);
const normalizedData = normalizeData({
users: [
{ id: 1, name: 'Chris', bestFriendId: 2 }
],
_users: [
{ id: 2, name: 'Joao' }
]
});
console.log(normalizedData);
this.user = this.store.push(normalizedData);
const james = this.store.peekRecord('user', '3');
this.user.bestFriend = james;
}
}
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { belongsTo, hasMany } from 'ember-data/relationships';
export default class extends Model {
@attr name;
@belongsTo('user', { async: false, inverse: null }) bestFriend;
get bestFriendId() {
return this.belongsTo('bestFriend').id();
}
}
<h1>Welcome to {{this.user.name}}</h1>
<h2>Hello {{this.user.bestFriend.name}}</h2>
<h3>Real Best Friend ID is {{this.user.bestFriend.id}}</h3>
<h3>Best Friend ID is {{this.user.bestFriendId}}</h3>
<br>
<br>
{{outlet}}
<br>
<br>
{
"version": "0.17.1",
"EmberENV": {
"FEATURES": {},
"_TEMPLATE_ONLY_GLIMMER_COMPONENTS": false,
"_APPLICATION_TEMPLATE_WRAPPER": true,
"_JQUERY_INTEGRATION": true
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js",
"ember": "3.18.1",
"ember-template-compiler": "3.18.1",
"ember-testing": "3.18.1"
},
"addons": {
"@glimmer/component": "1.0.0",
"ember-data": "3.18.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment