relay-fragments-patterns
БесплатноБез исполняемых скриптовНе проверенUse when relay fragment composition, data masking, colocation, and container patterns for React applications.
от TheBushidoCollective★ 202 звезды на GitHubОб этом скилле
Relay Fragments Patterns
Master Relay's fragment composition for building maintainable React applications with proper data dependencies and component colocation.
Overview
Relay fragments enable component-level data declaration with automatic composition, data masking, and optimal data fetching. Fragments colocate data requirements with components for better maintainability.
Installation and Setup
Installing Relay
# Install Relay packages
npm install react-relay relay-runtime
# Install Relay compiler
npm install --save-dev relay-compiler babel-plugin-relay
# Install GraphQL
npm install graphql
Relay Configuration
// relay.config.js
module.exports = {
src: './src',
schema: './schema.graphql',
exclude: ['**/node_modules/**', '**/__mocks__/**', '**/__generated__/**'],
language: 'typescript',
artifactDirectory: './src/__generated__'
};
// package.json
{
"scripts": {
"relay": "relay-compiler",
"relay:watch": "relay-compiler --watch"
}
}
Environment Setup
// RelayEnvironment.js
import {
Environment,
Network,
RecordSource,
Store
} from 'relay-runtime';
function fetchQuery(operation, variables) {
return fetch('http://localhost:4000/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify({
query: operation.text,
variables
})
}).then(response => response.json());
}
const environment = new Environment({
network: Network.create(fetchQuery),
store: new Store(new RecordSource())
});
export default environment;
Core Patterns
1. Basic Fragment Definition
// PostCard.jsx
import { graphql, useFragment } from 'react-relay';
const PostCardFragment = graphql`
fragment PostCard_post on Post {
id
title
excerpt
publishedAt
author {
name
avatar
}
}
`;
function PostCard({ post }) {
const data = useFragment(PostCardFragment, post);
return (
<article>
<h2>{data.title}</h2>
<p>{data.excerpt}</p>
<div>
<img src={data.author.avatar} alt={data.author.name} />
<span>{data.author.name}</span>
</div>
<time>{data.publishedAt}</time>
</article>
);
}
export default PostCard;
2. Fragment Composition
// UserProfile.jsx
const UserProfileFragment = graphql`
fragment UserProfile_user on User {
id
name
bio
...UserAvatar_user
...UserStats_user
}
`;
function UserProfile({ user }) {
const data = useFragment(UserProfileFragment, user);
return (
<div>
<h1>{data.name}</h1>
<p>{data.bio}</p>
<UserAvatar user={data} />
<UserStats user={data} />
</div>
);
}
// UserAvatar.jsx
const UserAvatarFragment = graphql`
fragment UserAvatar_user on User {
name
avatar
isOnline
}
`;
function UserAvatar({ user }) {
const data = useFragment(UserAvatarFragment, user);
return (
<div className="avatar-container">
<img src={data.avatar} alt={data.name} />
{data.isOnline && <span className="online-indicator" />}
</div>
);
}
// UserStats.jsx
const UserStatsFragment = graphql`
fragment UserStats_user on User {
postsCount
followersCount
followingCount
}
`;
function UserStats({ user }) {
const data = useFragment(UserStatsFragment, user);
return (
<div className="stats">
<div>Posts: {data.postsCount}</div>
<div>Followers: {data.followersCount}</div>
<div>Following: {data.followingCount}</div>
</div>
);
}
3. Fragment Arguments
// Post.jsx
const PostFragment = graphql`
fragment Post_post on Post
@argumentDefinitions(
includeComments: { type: "Boolean!", defaultValue: false }
commentsFirst: { type: "Int", defaultValue: 10 }
) {
id
title
body
comments(first: $commentsFirst) @include(if: $includeComments) {
edges {
node {
...Comment_comment
}
}
}
}
`;
function Post({ post, showComments = false }) {
const data = useFragment(
PostFragment,
post,
{
includeComments: showComments,
commentsFirst: 20
}
);
return (
<article>
<h1>{data.title}</h1>
<div>{data.body}</div>
{showComments && (
<CommentsList comments={data.comments.edges.map(e => e.node)} />
)}
</article>
);
}
4. Data Masking
// Parent component
const ParentFragment = graphql`
fragment Parent_data on Query {
user {
id
...Child_user
}
}
`;
function Parent({ data }) {
const parentData = useFragment(ParentFragment, data);
// parentData.user only contains id and fragment reference
// Cannot access user.name here (data masking)
return (
<div>
<h1>User ID: {parentData.user.id}</h1>
<Child user={parentData.user} />
</div>
)
Установить relay-fragments-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadWriteEditGrepGlobBashFAQ
Что делает скилл relay-fragments-patterns?
Use when relay fragment composition, data masking, colocation, and container patterns for React applications.
Как установить скилл relay-fragments-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл relay-fragments-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic