Skip to content

Commit 2c04e97

Browse files
committed
Allow overriding data while saving
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.
1 parent 8814006 commit 2c04e97

2 files changed

Lines changed: 37 additions & 4 deletions

File tree

src/Model.js

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -620,15 +620,18 @@ export default class Model {
620620
}
621621

622622
@action
623-
save(options = {}) {
623+
save({ data = {}, mapData = (x) => x, ...options } = {}) {
624624
this.clearValidationErrors();
625625
return this.wrapPendingRequestCount(
626626
this.__getApi()
627627
.saveModel({
628628
url: options.url || this.url,
629-
data: this.toBackend({
630-
fields: options.fields,
631-
onlyChanges: options.onlyChanges,
629+
data: mapData({
630+
...this.toBackend({
631+
fields: options.fields,
632+
onlyChanges: options.onlyChanges,
633+
}),
634+
...data,
632635
}),
633636
isNew: this.isNew,
634637
requestOptions: omit(options, 'url'),

src/__tests__/Model.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1068,6 +1068,36 @@ describe('requests', () => {
10681068
return animal.save({ params: { branch_id: 1 } });
10691069
});
10701070

1071+
test('save with custom data', () => {
1072+
const animal = new Animal();
1073+
mock.onAny().replyOnce(config => {
1074+
expect(JSON.parse(config.data)).toEqual({ id: null, name: '', extra_data: 'can be saved' });
1075+
return [201, {}];
1076+
});
1077+
1078+
return animal.save({ data: { extra_data: 'can be saved' } });
1079+
});
1080+
1081+
test('save with mapped data', () => {
1082+
const animal = new Animal();
1083+
mock.onAny().replyOnce(config => {
1084+
expect(JSON.parse(config.data)).toEqual({ id: 'overwritten', name: '' });
1085+
return [201, {}];
1086+
});
1087+
1088+
return animal.save({ mapData: data => ({ ...data, id: 'overwritten' }) });
1089+
});
1090+
1091+
test('save with custom and mapped data', () => {
1092+
const animal = new Animal();
1093+
mock.onAny().replyOnce(config => {
1094+
expect(JSON.parse(config.data)).toEqual({ id: 'overwritten', name: '', extra_data: 'can be saved' });
1095+
return [201, {}];
1096+
});
1097+
1098+
return animal.save({ data: { extra_data: 'can be saved' }, mapData: data => ({ ...data, id: 'overwritten' }) });
1099+
});
1100+
10711101
test('save all with relations', () => {
10721102
const animal = new Animal(
10731103
{

0 commit comments

Comments
 (0)