Skip to content

Instantly share code, notes, and snippets.

@runspired
Created October 5, 2018 19:09
Show Gist options
  • Save runspired/597ff8ccc4e9a06ff26c1754ba108fb3 to your computer and use it in GitHub Desktop.
Save runspired/597ff8ccc4e9a06ff26c1754ba108fb3 to your computer and use it in GitHub Desktop.
Coalesce findHasMany within adapter Twiddle
import Adapter from 'ember-data/adapters/json-api';
import { Promise, resolve, all } from 'rsvp';
import Ember from 'ember';
const { run } = Ember;
const PETS = {
'1': { name: 'Shen', owner: '1' },
'2': { name: 'Pirate', owner: '1' },
'3': { name: 'Rebel', owner: '2' },
'4': { name: 'Messi', owner: '2' },
'5': { name: 'Lion', owner: '3' },
'6': { name: 'Beast', owner: '3' },
};
function getPet(id) {
return {
type: 'pet',
id,
attributes: {
name: PETS[id].name
},
relationships: {
owner: {
data: { type: 'person', id: PETS[id].owner }
}
}
}
}
function getPets(ids) {
alert(`Coalesced Request For ${ids.join(', ')}`);
return resolve({
data: ids.map(getPet)
});
}
export default class ApplicationAdapter extends Adapter {
constructor() {
super(...arguments);
this.coalescedResourceFinds = new Map();
}
_flushCoalescedFind(type) {
let map = this.coalescedResourceFinds;
let finds = map.get(type);
map.delete(type);
let ids = Object.keys(finds);
getPets(ids).then(doc => {
// in real life we would normalize here first
// but since we are already json-api we are good
let { data } = doc;
if (!Array.isArray(data)) {
throw new Error('wrong stuff bud');
}
let lookupDict = Object.create(null);
data.forEach(resource => {
if (resource.type === type) {
lookupDict[resource.id] = resource;
}
});
ids.forEach(id => {
let resource = lookupDict[id];
if (!resource) {
// probably actually reject
throw new Error('missing stuff');
}
// resolve the original request
finds[id]({ data: resource });
});
// make sure all returned records are pushed,
// not just the specifically requested ones
this.store.push(doc);
});
}
findResource({ type, id }) {
let map = this.coalescedResourceFinds;
let finds = map.get(type);
if (!finds) {
finds = Object.create(null);
map.set(type, finds);
run.next(() => {
this._flushCoalescedFind(type);
});
// de-dupe duplicate finds
} else if (finds[id]) {
return finds[id];
}
return new Promise(resolveFind => {
finds[id] = resolveFind;
});
}
findHasMany(store, snapshot, link, relationshipMeta) {
let promises = snapshot.hasMany(relationshipMeta.key)
.map(i => {
return this.findResource({
type: relationshipMeta.type,
id: i.id
});
});
return all(promises).then(results => {
return {
data: results.map(result => result.data)
};
});
}
}
import Ember from 'ember';
export default Ember.Controller.extend({
init() {
this._super(...arguments);
this.people = this.store.push({
data: [
{
type: 'person',
id: '1',
attributes: { name: 'Chris' },
relationships: {
pets: {
data: [
{ id: '1', type: 'pet' },
{ id: '2', type: 'pet' }
],
links: {
related: './person/1/pets'
}
}
}
},
{
type: 'person',
id: '2',
attributes: { name: 'James' },
relationships: {
pets: {
data: [
{ id: '3', type: 'pet' },
{ id: '4', type: 'pet' }
],
links: {
related: './person/2/pets'
}
}
}
},
{
type: 'person',
id: '3',
attributes: { name: '@runspired' },
relationships: {
pets: {
data: [
{ id: '5', type: 'pet' },
{ id: '6', type: 'pet' }
],
links: {
related: './person/3/pets'
}
}
}
},
]
});
}
});
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { belongsTo, hasMany } from 'ember-data/relationships';
export default Model.extend({
name: attr(),
pets: hasMany('pet', { inverse: 'owner', async: true })
});
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { belongsTo, hasMany } from 'ember-data/relationships';
export default Model.extend({
name: attr(),
owner: belongsTo('person', { inverse: 'pets', async: false })
});
<h2>Coalescing findHasMany Requests</h2>
<p>Coalescing within the adapter itself when links and data are both present</p>
<br>
<ul>
{{#each people as |person|}}
<li>
{{person.name}}<br>Pets:
<ul>
{{#each person.pets as |pet|}}
<li>{{pet.name}}</li>
{{/each}}
</ul>
</li>
{{/each}}
</ul>
<br>
{{outlet}}
<br>
<br>
{
"version": "0.15.1",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js",
"ember": "3.4.3",
"ember-template-compiler": "3.4.3",
"ember-testing": "3.4.3"
},
"addons": {
"ember-data": "3.4.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment