Forked from nickhudkins/createFragmentContainer.js
Created
February 14, 2019 02:02
-
-
Save sibelius/6d404ea4efca1172c5bc457514b0c07f to your computer and use it in GitHub Desktop.
Data Masking with Apollo / GraphQL Anywhere
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { filter } from 'graphql-anywhere'; | |
import hoistNonReactStatic from 'hoist-non-react-statics'; | |
/* | |
* createFragmentContainer returns a component which expects props that match | |
* WrappedComponent's fragment names, and provides data masking | |
*/ | |
export default function createFragmentContainer(WrappedComponent) { | |
const Enhanced = props => { | |
const fragmentKeys = Object.keys(WrappedComponent.fragments); | |
const fragmentDataProps = fragmentKeys.reduce((accProps, fragmentKey) => { | |
const fragment = WrappedComponent.fragments[fragmentKey]; | |
return { | |
...accProps, | |
// `filter` from graphql-anywhere is doing the heavy lifting here of masking | |
[fragmentKey]: filter(fragment, props[fragmentKey] || {}), | |
}; | |
}, {}); | |
return <WrappedComponent {...props} {...fragmentDataProps} />; | |
}; | |
// retain fragments defined statically on WrappedComponent | |
hoistNonReactStatic(Enhanced, WrappedComponent); | |
return Enhanced; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment