From 5d26790a32ccd9660cff6d7e6d5851b2cfcd2f21 Mon Sep 17 00:00:00 2001 From: Artur Arseniev Date: Sun, 24 Mar 2019 17:13:58 +0100 Subject: [PATCH] Add `fetchOptions` for the RemoteStorage. Closes #1885 --- src/storage_manager/config/config.js | 10 +++++++++- src/storage_manager/model/RemoteStorage.js | 15 ++++++++++++--- test/specs/storage_manager/model/Models.js | 17 +++++++++++++++++ 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/storage_manager/config/config.js b/src/storage_manager/config/config.js index e0a6fb034..b63b796b7 100644 --- a/src/storage_manager/config/config.js +++ b/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: '' }; diff --git a/src/storage_manager/model/RemoteStorage.js b/src/storage_manager/model/RemoteStorage.js index ba78518b6..c20fdb9f9 100644 --- a/src/storage_manager/model/RemoteStorage.js +++ b/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() diff --git a/test/specs/storage_manager/model/Models.js b/test/specs/storage_manager/model/Models.js index 6cd4a1184..b81565e0b 100644 --- a/test/specs/storage_manager/model/Models.js +++ b/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); + }); }); } };