Skip to content
GraphQL

4. GraphQL Advanced Features Hindi – Fragments Aliases Variables

May 31, 2026 14 min read

नमस्ते दोस्तों!

स्वागत है The Easy Master पर!

आपने GraphQL queries aur mutations likhna seekh liya. Ab aapke queries kaam toh kar rahe hain, lekin kya woh reusable, dynamic, aur maintainable hain? Agar aap same fields baar-baar likh rahe ho, alag-alag queries mein copy-paste kar rahe ho, toh aap GraphQL ki poori power use nahi kar rahe.

Jab maine pehli baar medium-scale project mein GraphQL use kiya, toh mujhe realise hua ki mere queries bohot repetitive ho rahe hain. Har query mein same fields (id, name, email, createdAt) likhna pad raha tha. Phir maine fragments seekhe – aur boilerplate 70% kam ho gaya. Aliases ne ek hi query mein multiple same-type requests bhejne mein help ki. Aur variables ne queries ko dynamic aur secure bana diya.

Is GraphQL advanced features Hindi article mein main aapko ye teen powerful concepts sikhata hoon:

✅ Fragments – reusable field sets, fragment spread operator, use cases
✅ Fragments with arguments – $deviceType jaise use cases
✅ Aliases – ek hi query mein ek field ko multiple baar different names ke saath
✅ Variables – dynamic queries, input validation, security (prevent injection)
✅ Default variables – optional variables ke liye default values
✅ Practical examples – real API queries mein implementation
✅ Best practices aur common mistakes

Chaliye GraphQL queries ko reusable, dynamic aur maintainable banate hain! 🚀

1. Reusable Queries Ki Zaroorat – Why Advanced Features?

GraphQL ki power flexibility hai, lekin agar aap queries likhte waqt repetitive kaam kar rahe ho, toh aapka code maintain karna mushkil ho jata hai.

Problem Statements:

ProblemWithout Fragments/Aliases/VariablesWith Advanced Features
Same fields multiple queries mein repeatBoilerplate code, change ek field mein karna hai toh saari queries mein change karoFragment define karo, ek jagah change karo
Ek hi query mein same field alag arguments ke saathName conflict (you can’t have two user fields)Aliases use karo – user1: user(id:1), user2: user(id:2)
Dynamic values (search term, page number)String concatenation – insecure, hard to readVariables – type-safe, secure, reusable

GraphQL advanced features queries ko professional banate hain – maintainable, type-safe, aur efficient.

2. Fragments – Field Sets Reuse Karein

Fragment ek reusable unit hai jo fields ke set ko define karta hai. Aap fragment ko multiple queries aur mutations mein include kar sakte ho using spread operator (...).

2.1 Fragment Syntax aur Definition

graphql

Code
fragment UserFields on User {
  id
  name
  email
  profilePicture
  createdAt
}

Rules:

  • Fragment ka naam unique hona chahiye
  • on keyword ke baad type name (e.g., User, Post)
  • Fragment mein nested fields aur sub-fragments bhi ho sakte hain

2.2 Spread Operator (...FragmentName)

Fragment ko query mein include karna:

graphql

Code
query GetUserProfile {
  user(id: "123") {
    ...UserFields
    bio
    postsCount
  }
}

Fully expanded query jaisa behave karega – fields id, name, email, profilePicture, createdAt, plus bio and postsCount.

2.3 Fragments with Arguments

Kai baar fragment ke fields arguments accept karna chahte ho (e.g., posts(limit: 5)). Fragments themselves don’t take arguments, but you can use variables inside fragments.

Alternatively, use fragment arguments via directives (GraphQL spec doesn’t have native fragment arguments, but some tools support @include/@skip directives).

2.4 Inline Fragments

Inline fragments use hoti hain jab aap interface ya union type ke specific fields access kar rahe ho.

graphql

Code
query Search {
  search(term: "graphql") {
    __typename
    ... on Article {
      title
      body
    }
    ... on Video {
      url
      duration
    }
  }
}

2.5 Fragment Collocation

Best practice: fragments ko un components ke saath define karo jo unhe use karte hain (React components mein).

JavaScript
// UserCard.js
export const USER_CARD_FRAGMENT = gql`
  fragment UserCard on User {
    id
    name
    avatar
  }
`;

Isse fields aur components tightly coupled hote hain – change tracking easy ho jata hai.

3. Aliases – Conflict Solve Karein

Alias aapko ek hi query mein same field ko alag-alag arguments ke saath multiple baar request karne ki facility deta hai.

3.1 Ek Query Mein Multiple Same Type Requests

Without Aliases (Not possible):

graphql

Code
query {
  user(id: "1") { name }
  user(id: "2") { name }   # Error: field "user" conflict
}

With Aliases:

graphql

Code
query {
  user1: user(id: "1") {
    name
    email
  }
  user2: user(id: "2") {
    name
    email
  }
}

3.2 Real Use Case – Dashboard

graphql

Code
query DashboardData {
  totalUsers: usersCount
  activeUsers: usersCount(status: ACTIVE)
  recentPosts: posts(limit: 5) {
    id
    title
  }
  popularPosts: posts(sortBy: VIEWS, limit: 5) {
    id
    title
    viewCount
  }
}

Aliases se response mein totalUsers, activeUsers, recentPosts, popularPosts fields milega – clean aur predictable.

3.3 Aliases with Fragments

graphql

Code
query {
  user1: user(id: "1") {
    ...UserFields
  }
  user2: user(id: "2") {
    ...UserFields
  }
}

Same fragment dono aliases ke liye reuse hoga – dry code.

4. Variables – Dynamic Queries Banayein

Variables queries ko dynamic banate hain – aap query string mein hardcoded values ki jagah placeholders use karte ho, aur values alag se JSON map mein bhejte ho.

4.1 Variable Definition Syntax

graphql

Code
query GetUser($userId: ID!) {
  user(id: $userId) {
    name
    email
  }
}

Rules:

  • $userId – variable name (always starts with $)
  • ID! – variable type with non-null
  • Variables query string ke top par define hote hain

4.2 Variable Use in Queries/Mutations

Query mein variable ka use:

graphql

Code
query GetPost($postId: ID!, $withComments: Boolean!) {
  post(id: $postId) {
    title
    content
    comments @include(if: $withComments) {
      text
    }
  }
}

Client side (Apollo):

JavaScript
const { data } = useQuery(GET_POST, {
  variables: { postId: "123", withComments: true },
});

4.3 Default Values

Default values provide fallback when variable not provided:

graphql

Code
query GetProducts($limit: Int = 10, $offset: Int = 0) {
  products(limit: $limit, offset: $offset) {
    id
    name
  }
}

4.4 Variable Types

Variables scalar types (String, Int, Float, Boolean, ID) ke alawa input object types bhi accept kar sakte hain.

graphql

Code
query Search($input: SearchInput!) {
  search(input: $input) {
    results {
      id
      title
    }
  }
}

Where SearchInput is defined in schema.

4.5 Security Benefits

Variables queries ko injection-proof banate hain. Agar aap variables ki jagah string concatenation use karo:

JavaScript
// ❌ Bad: GraphQL injection risk
`query { user(id: "${userId}") { name } }`

Variables use karo – GraphQL parsers variables and query separately handle karte hain, isliye injection possible nahi hai.

5. Fragments + Variables + Aliases – Combine Karna

Teeno features ko combine karke powerful queries likhi ja sakti hain.

Example: Compare two users with posts

graphql

Code
fragment UserWithPosts on User {
  id
  name
  email
  posts(limit: $postsLimit) {
    id
    title
    createdAt
  }
}

query CompareUsers($userId1: ID!, $userId2: ID!, $postsLimit: Int = 5) {
  user1: user(id: $userId1) {
    ...UserWithPosts
    accountType
  }
  user2: user(id: $userId2) {
    ...UserWithPosts
    accountType
  }
}

Variables:

JSON
{
  "userId1": "123",
  "userId2": "456",
  "postsLimit": 10
}
  • Fragment – UserWithPosts reusable
  • Variables – $userId1, $userId2, $postsLimit dynamic
  • Aliases – user1 and user2 to differentiate

6. Hands-On – Real Examples

Example 1: User Profile Dashboard (Fragments)

Fragment definition:

graphql

Code
fragment ProfileFields on User {
  id
  name
  email
  avatar
  joinDate
}

Query using fragment:

graphql

Code
query UserProfile($userId: ID!) {
  user(id: $userId) {
    ...ProfileFields
    bio
    followersCount
    followingCount
    posts(limit: 10) {
      id
      title
      likeCount
    }
  }
}

Example 2: Compare Two Products (Aliases)

graphql

Code
query CompareProducts($id1: ID!, $id2: ID!) {
  productA: product(id: $id1) {
    id
    name
    price
    rating
    inStock
  }
  productB: product(id: $id2) {
    id
    name
    price
    rating
    inStock
  }
}

Variables:

JSON
{ "id1": "prod-100", "id2": "prod-200" }

Response structure:

JSON
{
  "data": {
    "productA": { "id": "prod-100", "name": "Laptop", ... },
    "productB": { "id": "prod-200", "name": "Mouse", ... }
  }
}

Example 3: Search with Pagination (Variables)

graphql

Code
query SearchProducts($searchTerm: String!, $limit: Int = 20, $offset: Int = 0) {
  products(search: $searchTerm, limit: $limit, offset: $offset) {
    id
    name
    price
    category
  }
  totalCount: productsCount(search: $searchTerm)
}

Variables:

JSON
{
  "searchTerm": "laptop",
  "limit": 10,
  "offset": 0
}

Frontend mein pagination ke liye offset update karte raho.

7. Best Practices – Production-Level Tips

✅ Always use variables – Never concatenate strings to build queries. Variables prevent injection and make queries reusable.

✅ Use fragments for field consistency – If a set of fields appears in multiple queries, create a fragment.

✅ Name fragments meaningfully – UserProfileFields, PostPreview, not Fragment1.

✅ Collocate fragments with components – Keep fragment definition near component that uses it.

✅ Use default values for optional variables – Makes queries self-documenting.

✅ Use __typename in inline fragments – Helps client-side cache normalization.

✅ Limit fragment nesting depth – Too many nested fragments hurt readability.

✅ Lint fragment usage – Tools like graphql-eslint can detect unused fragments.

✅ Use variables for environment-specific values – API endpoint, feature flags, etc.

✅ Keep query variable names consistent across client and server – Ease of debugging.

💡 Personal Experience: Maine ek project mein fragments use nahi kiye the – queries mein fields repeated the. Jab schema mein ek field rename karna pada, toh mujhe 15 queries update karni padi. Uske baad maine har component ke saath fragment collocate karna start kar diya. Ab agar field rename ho, toh sirf fragment change karna hota hai.

8. Common Mistakes (aur Unka Solution!)

MistakeWhy it’s wrongSolution
Hardcoding values in query instead of variablesSecurity risk (injection), not reusableUse $variableName and pass variables separately
Forgetting ! for required variablesClient might not send required value, leading to weird errorsUse $id: ID! when field is non-nullable
Fragment name conflictSame fragment name defined twice leads to errorUse meaningful namespaced names (e.g., UserProfileFields)
Not using ... before fragment nameFragment won’t be includedAlways use spread syntax ...FragmentName
Aliases without meaningful namesuser1, user2 fine, but data1, data2 unclearUse descriptive aliases (activeUsers, archivedUsers)
Overusing fragments for one-time useAdds complexityCreate fragments only when field set reused at least twice
Variable type mismatchPassing Int when String expectedCheck schema and use correct GraphQL variable type
Default values not matching type$limit: Int = "10" (string) invalidUse correct type: $limit: Int = 10

GraphQL injection: Variables are the only safe way to send dynamic values. String concatenation can allow malicious queries (e.g., "1; mutation { ... }"). Variables are typed and escaped automatically.

9. Resources – Cheat Sheet & Practice Prompts

📋 Fragment Cheat Sheet

graphql

Code
# Define fragment
fragment BookDetails on Book {
  id
  title
  author
  publishedYear
}

# Use fragment
query GetBooks {
  books {
    ...BookDetails
    genre
  }
}

# Fragment with sub-fragment
fragment AuthorDetails on Author {
  id
  name
  books {
    ...BookDetails
  }
}

📋 Alias Cheat Sheet

graphql

Code
query {
  oldData: posts(status: OLD) { id title }
  newData: posts(status: NEW) { id title }
}

📋 Variable Cheat Sheet

graphql

Code
# Query definition
query GetPaginatedPosts($page: Int!, $limit: Int = 10) {
  posts(page: $page, limit: $limit) { id title }
}

# Variables JSON
{
  "page": 2,
  "limit": 20
}

📋 Combine All

graphql

Code
fragment PostFragment on Post {
  id
  title
  author { name }
}

query GetDashboard($userId: ID!, $includeDrafts: Boolean = false) {
  recentPosts: posts(limit: 5) { ...PostFragment }
  userPosts: posts(authorId: $userId, includeDrafts: $includeDrafts) {
    ...PostFragment
    isDraft
  }
}

🧠 Practice Prompts

Beginner:

  • User fragment banao with fields id, name, email, avatar. Query mein user(id: $userId) fragment use karo.
  • Search query likho with variables $searchTerm and $limit. Pagination implement karo with $offset.

Intermediate:

  • Dashboard query likho – topProducts, newProducts, saleProducts – using aliases. Saare aliases same fragment use karein.
  • Fragment with arguments simulate karo using variables inside fragment – e.g., posts(limit: $postsLimit). Query mein $postsLimit variable pass karo.

Advanced:

  • Inline fragments use karo with union type SearchResult. Fragment ... on Article { title body } and ... on Video { title url }. Variables ke saath search term dynamic banao.
  • Nested fragments implement karo – PostFragment includes AuthorFragment. Query mein ...PostFragment spread karo.

10. FAQ

Q1: Fragments aur Inline fragments mein kya antar hai?

Named fragments reusable hoti hain – defined once and used many times with ...FragmentName. Inline fragments specific interface/union type fields access karne ke liye use hoti hain, aur woh query ke andar hi defined hoti hain.

Q2: Kya fragment arguments accept kar sakta hai?

GraphQL specification mein fragment arguments nahi hain. Lekin aap fragment ke andar variables use kar sakte ho – variables query level par define hote hain. Alternative: use @include/@skip directives.

Q3: Alias kyun use karein jab client side rename kar sakte ho?

Aliases server side rename karte hain – means response mein field name change ho jata hai. Client side rename sirf variable assignment hota hai. Aliases avoid name conflicts at the root level.

Q4: Variables mandatory kyun hai security ke liye?

Variables type-safe hoti hain – GraphQL automatically escapes and validates types. String concatenation injection vulnerabilities create kar sakti hai (e.g., user input containing " or } breaking the query).

Q5: Kya ek query mein multiple fragments ho sakte hain?

Haan – aap jitne chahe fragments define kar sakte ho. Each fragment must have a unique name and be defined on the correct type.

Q6: Fragments recursion support karte hain (e.g., Category with subcategories)?

Haan – fragment recursively use kar sakte ho (e.g., CategoryFragment { children { ...CategoryFragment } }). Lekin depth limit rakho to avoid infinite recursion.

Q7: Variables ki default value kaise set karein?

$limit: Int = 10 – default value 10. Agar variable pass nahi hua toh default use hoga.

Q8: Kya variable list type ho sakta hai?

Haan – $ids: [ID!]! is valid. Query mein where: { id: { in: $ids } } use kar sakte ho.

Q9: Fragment ko ek hi query mein multiple baar use kar sakte hain?

Haan – jaise fragment UserFields on User ko user1 { ...UserFields } and user2 { ...UserFields } dono jagah use kar sakte ho.

Q10: Aliases aur fragments combination ka real example?

Dashboard query: popular: products(limit: 5) { ...ProductFields }, recent: products(sortBy: DATE, limit: 5) { ...ProductFields }. Fragment ProductFields reused for both aliases – powerful combination.

11. Conclusion – Ab Aapki Baari!

Bahut badhiya! Aapne aaj GraphQL ke teen advanced features master kar liye:

✅ Fragments – reusable field sets, fragment spread, inline fragments
✅ Aliases – ek query mein same field multiple baar alag names ke saath
✅ Variables – dynamic, type-safe, secure queries
✅ Combining all three – professional-grade GraphQL queries
✅ Real examples – user dashboard, product comparison, pagination
✅ Best practices aur common mistakes – injection safety, fragment collocation

Ab aapki GraphQL queries pehle se zyada clean, maintainable aur dynamic ho jayengi. Fragments se boilerplate kam, aliases se conflicts resolve, variables se injection-free dynamic queries.

Aapki challenge: Apne existing query (e.g., user profile) ko fragments mein refactor karo, add variables for dynamic userId, aur agar same user type ke alag alag requests ho toh aliases use karo. Apna code comment mein share karo!

Next topic kya chahiye?

  • GraphQL Subscriptions – Real-time data?
  • GraphQL Federation (multiple GraphQL services)?
  • GraphQL Security (persisted queries, depth limiting)?

Comment mein batao!

The Easy Master ke saath GraphQL advanced features seekhte raho। Happy querying! 🚀

Resources

Additional Resources

Views: 441

TheEasyMaster

Author at The Easy Master.

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *