Skip to content

Instantly share code, notes, and snippets.

@runspired
Last active April 14, 2023 21:51
Show Gist options
  • Save runspired/54ff8f95e348b529ba3e2098598e1f9f to your computer and use it in GitHub Desktop.
Save runspired/54ff8f95e348b529ba3e2098598e1f9f to your computer and use it in GitHub Desktop.
Transactional Bulk Endpoint
import Controller from '@ember/controller';
import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { recordIdentifierFor } from '@ember-data/store';
let count = 2;
export default class ApplicationController extends Controller {
appName = 'Ember Twiddle';
@service store;
all = this.store.peekAll('audit');
@tracked records = [
this.store.push({
data: {
type: 'audit',
id: '1',
attributes: { name: 'Initial Audit' }
}
})
];
get savedRecords() {
return this.records.filter(r => !r.isNew);
}
get pendingRecords() {
return this.records.filter(r => r.isNew);
}
@action addNewRecord() {
const rCount = count++;
const audit = this.store.createRecord('audit', {
name: `new audit ${rCount}`,
count: rCount
});
this.records.push(audit);
this.records = this.records;
}
async mySaveRequestMethod(records) {
const fetchedJson = await Promise.resolve({
data: records.map(r => {
return { id: `${r.count}`, type: 'audit' };
})
});
const identifiers = records.map(r => recordIdentifierFor(r));
fetchedJson.data.forEach((resource, i) => {
resource.lid = identifiers[i].lid;
});
this.store.push(fetchedJson);
}
@action async bulkSave() {
const pending = this.pendingRecords;
await this.mySaveRequestMethod(pending);
}
}
import Model, { attr } from '@ember-data/model';
export default class extends Model {
@attr name;
@attr count;
}
<h1>Welcome to {{this.appName}}</h1>
<br>
<h2>All</h2>
<ul>
{{#each this.all as |record|}}
<li>{{record.name}} - {{record.id}}</li>
{{else}}
<p>No Records</p>
{{/each}}
</ul>
<h2>Saved</h2>
<ul>
{{#each this.savedRecords as |record|}}
<li>{{record.name}} - {{record.id}}</li>
{{else}}
<p>None Saved</p>
{{/each}}
</ul>
<h2>Pending</h2>
<ul>
{{#each this.pendingRecords as |record|}}
<li>{{record.name}}</li>
{{else}}
<p>None pending</p>
{{/each}}
</ul>
<button {{on "click" this.addNewRecord}}>Add New</button><br>
<button {{on "click" this.bulkSave}}>Save all</button>
<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