Skip to content

Instantly share code, notes, and snippets.

@sgwilym
Created March 12, 2019 09:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgwilym/a0c1bca61d5cadd35e7bda68222f48f3 to your computer and use it in GitHub Desktop.
Save sgwilym/a0c1bca61d5cadd35e7bda68222f48f3 to your computer and use it in GitHub Desktop.
// Example of what data masking gets us with Relay
const AdminList = createFragmentContainer(
(props) => <div>
{props.admins.map((admin) => <div>{admin.name}</div>)}
</div>,
{
admins: graphql`
fragment AdminList_admins on User @relay(plural: true) {
name
}
`
}
)
const ProjectDetails = createFragmentContainer(
(props) => <div>
<h1>Project</h1>
// If we accidentally pass the wrong object to AdminList, like project.members
// AdminList will throw errors when it renders, even though the data has the same shape
// thanks to data masking
<AdminList admins={props.project.members}/>
</div>,
{
project: graphql`
fragment ProjectDetails_project on Project {
admins {
... AdminList_admins
}
members {
name
}
}
`
}
)
// -------------------------------------
// Now…
// Doing what we can with Apollo + types
// and how it isn't quite the same
// Importing type generated by Apollo codegen
import { AdminUser } from '__generated__/AdminUser.ts';
// A separate fragment to compose into others
const AdminFragment = gql`
fragment AdminUser on User {
name
}
`;
interface AdminListProps {
admins: AdminUser[]
};
const AdminList = (props) =>
<div>
{props.admins.map((admin) => <div>{admin.name}</div>)}
</div>
// And the parent component
const ProjectDetailsFragment = gql`
fragment ProjectDetails on Project {
admins {
... AdminList_admins
}
members {
name
}
}
${AdminFragment}
`
const ProjectDetails = (props) =>
<div>
<h1>Project</h1>
// If we accidentally pass the wrong object to AdminList
// We'll never know because project.members conforms to the type of AdminUser[]!
<AdminList admins={props.project.members}/>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment