Skip to content

Commit

Permalink
Allow overriding data while saving
Browse files Browse the repository at this point in the history
Now you can add save({ data: {}, mapData: data => data }) to allow
overriding data send to the backend.

This only works for save atm, saveAll is unchanged for now.
  • Loading branch information
abzainuddin committed Nov 4, 2019
1 parent 8814006 commit 2c04e97
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -620,15 +620,18 @@ export default class Model {
}

@action
save(options = {}) {
save({ data = {}, mapData = (x) => x, ...options } = {}) {
this.clearValidationErrors();
return this.wrapPendingRequestCount(
this.__getApi()
.saveModel({
url: options.url || this.url,
data: this.toBackend({
fields: options.fields,
onlyChanges: options.onlyChanges,
data: mapData({
...this.toBackend({
fields: options.fields,
onlyChanges: options.onlyChanges,
}),
...data,
}),
isNew: this.isNew,
requestOptions: omit(options, 'url'),
Expand Down
30 changes: 30 additions & 0 deletions src/__tests__/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -1068,6 +1068,36 @@ describe('requests', () => {
return animal.save({ params: { branch_id: 1 } });
});
test('save with custom data', () => {
const animal = new Animal();
mock.onAny().replyOnce(config => {
expect(JSON.parse(config.data)).toEqual({ id: null, name: '', extra_data: 'can be saved' });
return [201, {}];
});
return animal.save({ data: { extra_data: 'can be saved' } });
});
test('save with mapped data', () => {
const animal = new Animal();
mock.onAny().replyOnce(config => {
expect(JSON.parse(config.data)).toEqual({ id: 'overwritten', name: '' });
return [201, {}];
});
return animal.save({ mapData: data => ({ ...data, id: 'overwritten' }) });
});
test('save with custom and mapped data', () => {
const animal = new Animal();
mock.onAny().replyOnce(config => {
expect(JSON.parse(config.data)).toEqual({ id: 'overwritten', name: '', extra_data: 'can be saved' });
return [201, {}];
});
return animal.save({ data: { extra_data: 'can be saved' }, mapData: data => ({ ...data, id: 'overwritten' }) });
});
test('save all with relations', () => {
const animal = new Animal(
{
Expand Down

0 comments on commit 2c04e97

Please sign in to comment.