Browse Source

Add `fetchOptions` for the RemoteStorage. Closes #1885

pull/1918/head
Artur Arseniev 7 years ago
parent
commit
5d26790a32
  1. 10
      src/storage_manager/config/config.js
  2. 15
      src/storage_manager/model/RemoteStorage.js
  3. 17
      test/specs/storage_manager/model/Models.js

10
src/storage_manager/config/config.js

@ -55,5 +55,13 @@ module.exports = {
// false: 'x-www-form-urlencoded'
contentTypeJson: true,
credentials: 'include'
credentials: 'include',
// Pass custom options to fetch API (remote storage)
// You can pass a simple object: { someOption: 'someValue' }
// or a function wich returns and object to add:
// currentOpts => {
// return currentOpts.method === 'post' ? { method: 'patch' } : {};
// }
fetchOptions: ''
};

15
src/storage_manager/model/RemoteStorage.js

@ -1,5 +1,5 @@
import fetch from 'utils/fetch';
import { isUndefined } from 'underscore';
import { isUndefined, isFunction } from 'underscore';
module.exports = require('backbone').Model.extend({
fetch,
@ -11,7 +11,8 @@ module.exports = require('backbone').Model.extend({
beforeSend() {},
onComplete() {},
contentTypeJson: false,
credentials: 'include'
credentials: 'include',
fetchOptions: ''
},
/**
@ -123,8 +124,16 @@ module.exports = require('backbone').Model.extend({
fetchOptions.body = body;
}
const fetchOpts = this.get('fetchOptions') || {};
const addOpts = isFunction(fetchOpts)
? fetchOpts(fetchOptions)
: fetchOptions;
this.onStart();
this.fetch(url, fetchOptions)
this.fetch(url, {
...fetchOptions,
...(addOpts || {})
})
.then(res =>
((res.status / 200) | 0) == 1
? res.text()

17
test/specs/storage_manager/model/Models.js

@ -141,6 +141,23 @@ module.exports = {
credentials: false
});
});
test('Load data with custom fetch options as function', () => {
const customOpts = { customOpt: 'customValue' };
obj = new RemoteStorage({
...storageOptions,
fetchOptions: () => {
return customOpts;
}
});
sinon
.stub(obj, 'fetch')
.returns(Promise.resolve(mockResponse({ data: 1 })));
obj.load(['item1', 'item2']);
const callResult = obj.fetch;
expect(callResult.called).toEqual(true);
expect(callResult.firstCall.args[1]).toMatchObject(customOpts);
});
});
}
};

Loading…
Cancel
Save