Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement initial default adapter for upcoming adapter pattern #51

Merged
merged 23 commits into from
Nov 28, 2017
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
c9c2a13
Add initial adapter pattern for collection.js
Nov 10, 2017
396fded
Add remaining adapter methods to existing actions
Nov 13, 2017
594737f
Fix linting
Nov 13, 2017
eb7f531
Move storageManager actions to shared adapter in in adapters/default.js
Nov 13, 2017
4dda476
Add missing adapters foldee to git
Nov 13, 2017
daf3c01
revert to basic function pattern
Nov 13, 2017
f3c7017
Make dispatch and getState available as options to all adapter actions
Nov 14, 2017
ab39813
Added collectionToIds and collectionToArray to the default adapter
Nov 15, 2017
5807638
Conditionally pass in adapter when its defined in typeOptions
Nov 15, 2017
3ee071f
Add the SYNC_COLLECTIONS reducer that merges new collections into the…
Nov 16, 2017
4fe6296
add additional makeBrainstemType actions that use adapter and add nee…
Nov 20, 2017
31f9d98
fix issues with validate + destroy specs
Nov 21, 2017
2656bf3
move option building to shared method
Nov 21, 2017
5e50c93
bump version to next beta
Nov 27, 2017
a0ea814
Prefer Object.assign with an empty object to prevent mutating the ori…
Nov 27, 2017
ab98fe0
Fix typo in spec assertion
Nov 27, 2017
201b48f
Add directions for running and testing example code in README
Nov 27, 2017
a1be14f
Use Object.assign with a new empty object in favor of mutating the ex…
Nov 28, 2017
2785ac7
Merge branch 'add_adapter_pattern' of https://github.com/mavenlink/br…
heyellieday Nov 28, 2017
b0d6aba
Merge branch 'add_adapter_pattern' of github.com:mavenlink/brainstem-…
shirish-pampoorickal Nov 28, 2017
424dd71
Bump version number to 0.0.35
Nov 28, 2017
1c56c06
Merge pull request #50 from mavenlink/make_brainstem_type_options
heyellieday Nov 28, 2017
e13303e
Merge branch 'master' into add_adapter_pattern
Nov 28, 2017
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -423,3 +423,10 @@ collectionActions.fetch('posts', {
## Local Development

In order to develop against a local checkout, run `yarn link` in `brainstem-redux`, then `yarn link brainstem-redux` in the project you want to use it in and restart webpack. Also, make sure to `yarn compile` when making changes in `brainstem-redux`.

## Running example

1. run `yarn start`
2. navigate to `http://localhost:8080/webpack-dev-server/`
3. click on `example`
4. view example app and type an approved string into the search bar
22 changes: 14 additions & 8 deletions lib/actions/collection.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { StorageManager } = require('brainstem-js');
Copy link
Contributor

@juanca juanca Nov 27, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removing the dependency to the StorageManager is fantastic! I know it's outta scope so I made a follow-up issue about removing it from the defaults as well:

#52

const defaultAdapter = require('../adapters/default');

const xhrs = {};

Expand All @@ -9,24 +9,30 @@ module.exports = {
postFetchAction,
preFetchAction,
trackKey,
adapter = defaultAdapter,
} = options;

const storageManager = StorageManager.get();

if (xhrs[trackKey] && xhrs[trackKey].state() === 'pending') xhrs[trackKey].abort();

return (dispatch) => {
return (dispatch, getState) => {
if (preFetchAction) dispatch(preFetchAction);

const xhr = storageManager.storage(brainstemKey)
.fetch(Object.assign(fetchOptions, { remove: false }));
const xhr = adapter.fetchCollection(brainstemKey, {
dispatch,
getState,
fetchOptions,
});

if (postFetchAction) xhr.done(collection => dispatch(postFetchAction(collection.pluck('id'))));
if (postFetchAction) {
xhr.done(collection =>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How is .done going to work when the XHR is not from jQuery?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have our mavenlink adapter return a deferred object like so:

fetchCollection: (brainstemKey, { dispatch, fetchOptions }) => {
       const deferred = $.Deferred();
 
       networkHelpers.fetchFromAPI(baseUrl, { params: fetchOptions.params, method: 'GET' })
         .then((result) => {
           dispatch(brainstemActions.syncCollections(result));
           deferred.resolve(result[brainstemKey]);
         });
 
       return deferred;
     },

dispatch(postFetchAction(adapter.collectionToIds(collection)))
);
}

if (trackKey) xhrs[trackKey] = xhr;

return new Promise((resolve, reject) => xhr
.done(collection => resolve(collection.map(model => model.attributes)))
.done(collection => resolve(adapter.collectionToArray(collection)))
Copy link
Contributor

@juanca juanca Nov 27, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the use-case for overriding collection.map? EDIT: And I'm assuming it's the same for overriding model.get('id')?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are delegating the handling of items in a collection to the adapter. Brainstem redux is now indifferent to the shape of the collection being passed in.

.fail(reject)
);
};
Expand Down
54 changes: 31 additions & 23 deletions lib/actions/model.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { StorageManager } = require('brainstem-js');
const $ = require('jquery');
const defaultAdapter = require('../adapters/default');

const xhrs = {};

Expand All @@ -10,20 +10,21 @@ module.exports = {
postFetchAction,
preFetchAction,
trackKey,
adapter = defaultAdapter,
} = options;

const storageManager = StorageManager.get();

if (xhrs[trackKey] && xhrs[trackKey].state() === 'pending') xhrs[trackKey].abort();

return (dispatch) => {
return (dispatch, getState) => {
if (preFetchAction) dispatch(preFetchAction);

const Model = storageManager.storage(brainstemKey).model;
const xhr = new Model({ id: modelId })
.fetch(Object.assign(fetchOptions, { remove: false }));
const xhr = adapter.fetchModel(brainstemKey, modelId, {
dispatch,
getState,
fetchOptions,
});

if (postFetchAction) xhr.done(model => dispatch(postFetchAction(model.get('id'))));
if (postFetchAction) xhr.done(model => dispatch(postFetchAction(adapter.modelToId(model))));

if (trackKey) xhrs[trackKey] = xhr;

Expand All @@ -37,18 +38,19 @@ module.exports = {
preSaveAction,
postSaveAction,
trackKey,
adapter = defaultAdapter,
} = options;

const storageManager = StorageManager.get();

if (xhrs[trackKey] && xhrs[trackKey].state() === 'pending') xhrs[trackKey].abort();

return (dispatch) => {
return (dispatch, getState) => {
if (preSaveAction) dispatch(preSaveAction);

const Model = storageManager.storage(brainstemKey).model;
let xhr = new Model({ id: modelId })
.save(attributes, saveOptions);
let xhr = adapter.saveModel(brainstemKey, modelId, attributes, {
dispatch,
getState,
saveOptions,
});

// backbone returns false when the model is invalid
if (!xhr.then) {
Expand All @@ -71,17 +73,21 @@ module.exports = {
},

destroy(brainstemKey, modelId, options = {}) {
const storageManager = StorageManager.get();
const {
deleteOptions = {},
trackKey,
adapter = defaultAdapter,
} = options;

if (xhrs[trackKey] && xhrs[trackKey].state() === 'pending') xhrs[trackKey].abort();

return () => {
const Model = storageManager.storage(brainstemKey).model;
const xhr = new Model({ id: modelId }).destroy(deleteOptions);
return (dispatch, getState) => {
const xhr = adapter.destroyModel(brainstemKey, modelId, {
dispatch,
getState,
deleteOptions,
});

if (trackKey) xhrs[trackKey] = xhr;

return xhr;
Expand All @@ -93,15 +99,17 @@ module.exports = {
validateOptions = {},
preValidateAction,
postValidateAction,
adapter = defaultAdapter,
} = options;

const storageManager = StorageManager.get();

return (dispatch) => {
return (dispatch, getState) => {
if (preValidateAction) dispatch(preValidateAction);

const Model = storageManager.storage(brainstemKey).model;
const validationErrors = new Model().validate(attributes, validateOptions);
const validationErrors = adapter.validateModel(brainstemKey, attributes, {
dispatch,
getState,
validateOptions,
});

if (postValidateAction) { dispatch(postValidateAction(validationErrors)); }

Expand Down
34 changes: 34 additions & 0 deletions lib/adapters/default.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const { StorageManager } = require('brainstem-js');

module.exports = {
fetchCollection: (brainstemKey, options) => {
const storageManager = StorageManager.get();
return storageManager.storage(brainstemKey)
.fetch(Object.assign({}, options.fetchOptions, { remove: false }));
},
fetchModel: (brainstemKey, modelId, options) => {
const storageManager = StorageManager.get();
const Model = storageManager.storage(brainstemKey).model;
return new Model({ id: modelId })
.fetch(Object.assign({}, options.fetchOptions, { remove: false }));
},
saveModel: (brainstemKey, modelId, attributes, options) => {
const storageManager = StorageManager.get();
const Model = storageManager.storage(brainstemKey).model;
return new Model({ id: modelId })
.save(attributes, options.saveOptions);
},
destroyModel: (brainstemKey, modelId, options) => {
const storageManager = StorageManager.get();
const Model = storageManager.storage(brainstemKey).model;
return new Model({ id: modelId }).destroy(options.deleteOptions);
},
validateModel: (brainstemKey, attributes, options) => {
const storageManager = StorageManager.get();
const Model = storageManager.storage(brainstemKey).model;
return new Model().validate(attributes, options.validateOptions);
},
collectionToIds: collection => collection.pluck('id'),
collectionToArray: collection => collection.map(model => model.attributes),
modelToId: model => model.get('id'),
};
3 changes: 3 additions & 0 deletions lib/reducers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
*/

const updateModel = require('./update-model');
const syncCollections = require('./sync-collections');
const removeModel = require('./remove-model');
const initialState = require('./initial-state');

Expand All @@ -24,6 +25,8 @@ module.exports = (state = initialState(), action) => {
return updateModel(state, action);
case 'REMOVE_MODEL':
return removeModel(state, action);
case 'SYNC_COLLECTIONS':
return syncCollections(state, action);
default:
return state;
}
Expand Down
15 changes: 15 additions & 0 deletions lib/reducers/sync-collections.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module.exports = (state, action) => {
const mergedCollections = {};
const { collections } = action.payload;
const collectionNames = Object.keys(collections);

collectionNames.forEach((collectionName) => {
mergedCollections[collectionName] = Object.assign(
{},
state[collectionName],
collections[collectionName],
);
});

return Object.assign({}, state, mergedCollections);
};
17 changes: 12 additions & 5 deletions lib/types/make-brainstem-type.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,16 @@ const defaultTypeOptions = {
};

module.exports = function makeBrainstemType(brainstemKey, typeOptions = defaultTypeOptions) {
const mergedOptions = { ...defaultTypeOptions, ...typeOptions };
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Object.assign and the rest of the spreads please.


const buildActionOptions = (options) => {
const { adapter } = mergedOptions;
return adapter ? { ...options, adapter } : options;
};

function all(state) {
return Object.keys(state.brainstem[brainstemKey])
.filter(id => typeOptions.filterPredicate(state.brainstem[brainstemKey][id]))
.filter(id => mergedOptions.filterPredicate(state.brainstem[brainstemKey][id]))
.reduce((memo, id) => {
memo[id] = state.brainstem[brainstemKey][id]; // eslint-disable-line no-param-reassign
return memo;
Expand Down Expand Up @@ -37,19 +44,19 @@ module.exports = function makeBrainstemType(brainstemKey, typeOptions = defaultT
}

function fetchAll(options) {
return collectionActions.fetch(brainstemKey, options);
return collectionActions.fetch(brainstemKey, buildActionOptions(options));
}

function fetch(id, options) {
return modelActions.fetch(brainstemKey, id, options);
return modelActions.fetch(brainstemKey, id, buildActionOptions(options));
}

function save(id, attributes, options) {
return modelActions.save(brainstemKey, id, attributes, options);
return modelActions.save(brainstemKey, id, attributes, buildActionOptions(options));
}

function destroy(id, options) {
return modelActions.destroy(brainstemKey, id, options);
return modelActions.destroy(brainstemKey, id, buildActionOptions(options));
}

function matchesAction({ meta, payload }) {
Expand Down
Loading