Skip to content

Instantly share code, notes, and snippets.

@sibelius
Forked from nickhudkins/createFragmentContainer.js
Created February 14, 2019 02:02
Show Gist options
  • Save sibelius/6d404ea4efca1172c5bc457514b0c07f to your computer and use it in GitHub Desktop.
Save sibelius/6d404ea4efca1172c5bc457514b0c07f to your computer and use it in GitHub Desktop.
Data Masking with Apollo / GraphQL Anywhere
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