<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ümit Havare on Medium]]></title>
        <description><![CDATA[Stories by Ümit Havare on Medium]]></description>
        <link>https://medium.com/@umithavare?source=rss-22f7fc910579------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-BywN_WURNAcVFdqacwluw.jpeg</url>
            <title>Stories by Ümit Havare on Medium</title>
            <link>https://medium.com/@umithavare?source=rss-22f7fc910579------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 11:18:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@umithavare/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Resolvers, Relay & the Node Pattern — From Basics to Distributed GraphQL with Fusion]]></title>
            <link>https://medium.com/@umithavare/resolvers-relay-the-node-pattern-from-basics-to-distributed-graphql-with-fusion-6fcb87edac19?source=rss-22f7fc910579------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fcb87edac19</guid>
            <category><![CDATA[relay]]></category>
            <category><![CDATA[resolver]]></category>
            <category><![CDATA[fusion]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[hot-chocolate]]></category>
            <dc:creator><![CDATA[Ümit Havare]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 07:24:45 GMT</pubDate>
            <atom:updated>2026-03-09T07:24:45.695Z</atom:updated>
            <content:encoded><![CDATA[<h3>Resolvers, Relay &amp; the Node Pattern in HotChocolate v14 — From Basics to Distributed GraphQL with Fusion</h3><p>A comprehensive, example-driven guide to building GraphQL APIs with HotChocolate v14 on .NET 8 — from basic resolvers to the Relay Global Object Identification spec, and finally composing distributed microservices with Fusion Gateway.</p><h3>Table of Contents</h3><ol><li>What Is a Resolver?</li><li>Basic Resolver Examples</li><li>Resolvers with Dependency Injection</li><li>Type Extension Resolvers</li><li>Solving the N+1 Problem with DataLoaders</li><li>The Relay Specification — Global Object Identification &amp; the Node Pattern</li><li>Fusion — Distributed GraphQL Gateway</li><li>How Node Resolution Works Inside the Fusion Gateway</li></ol><h3>1. What Is a Resolver?</h3><p>In GraphQL, every single field in your schema is backed by a <strong>resolver</strong> — a function that determines where and how the data for that field is fetched. If you come from a REST background, think of resolvers as the equivalent of controller action methods, but with one critical difference: in REST, a single endpoint returns an entire resource; in GraphQL, each field has its own resolver.</p><p>Consider this query:</p><pre>query {<br>  user {<br>    name<br>    email<br>  }<br>}</pre><p>Behind the scenes, the following happens:</p><ol><li>The resolver for the user field runs → fetches the User object.</li><li>The resolver for the name field runs → extracts name from the User object.</li><li>The resolver for the email field runs → extracts email from the User object.</li></ol><p>In HotChocolate, simple property access (like name and email) is resolved automatically by the framework — you don&#39;t need to write anything for them. You only write explicit resolvers for fields that require computation, additional database calls, or custom business logic.</p><h3>2. Basic Resolver Examples</h3><h3>2.1 The Simplest Possible Resolver</h3><p>In HotChocolate v14, any class registered as a Query type automatically turns its public methods into GraphQL fields.</p><pre>// Types/Query.cs<br>public class Query<br>{<br>    // This method automatically becomes the &quot;greeting&quot; field.<br>    // GraphQL: query { greeting }<br>    public string GetGreeting() =&gt; &quot;Hello, World!&quot;;<br>}</pre><pre>// Program.cs<br>var builder = WebApplication.CreateBuilder(args);</pre><pre>builder.Services<br>    .AddGraphQLServer()<br>    .AddQueryType&lt;Query&gt;();</pre><pre>var app = builder.Build();<br>app.MapGraphQL(); // Creates the /graphql endpoint by default<br>app.Run();</pre><p>Query and result:</p><pre>query {<br>  greeting<br>}</pre><pre>{<br>  &quot;data&quot;: {<br>    &quot;greeting&quot;: &quot;Hello, World!&quot;<br>  }<br>}</pre><blockquote><strong><em>Naming Convention:</em></strong><em> HotChocolate strips the </em><em>Get prefix and converts the rest to camelCase. </em><em>GetGreeting() becomes </em><em>greeting in the schema.</em></blockquote><h3>2.2 Resolvers with Parameters</h3><p>Method parameters automatically become GraphQL arguments.</p><pre>// Types/Query.cs<br>public class Query<br>{<br>    // GraphQL: query { greeting(name: &quot;Ali&quot;) }<br>    public string GetGreeting(string name) =&gt; $&quot;Hello, {name}!&quot;;<br><br>// Multiple parameters<br>    // GraphQL: query { calculateAge(birthYear: 1990, currentYear: 2026) }<br>    public int GetCalculateAge(int birthYear, int currentYear)<br>        =&gt; currentYear - birthYear;<br>}</pre><h3>2.3 Returning Objects and Lists</h3><pre>// Models/Book.cs<br>public class Book<br>{<br>    public int Id { get; set; }<br>    public string Title { get; set; } = default!;<br>    public string Author { get; set; } = default!;<br>    public decimal Price { get; set; }<br>    public DateTime PublishedDate { get; set; }<br>}</pre><pre>// Types/Query.cs<br>public class Query<br>{<br>    // Returns a single object<br>    // GraphQL: query { book(id: 1) { id title author price } }<br>    public Book? GetBook(int id)<br>    {<br>        var books = GetSampleBooks();<br>        return books.FirstOrDefault(b =&gt; b.Id == id);<br>    }<br><br>// Returns a list<br>    // GraphQL: query { books { id title author } }<br>    public List&lt;Book&gt; GetBooks() =&gt; GetSampleBooks();<br>    private List&lt;Book&gt; GetSampleBooks() =&gt;<br>    [<br>        new Book<br>        {<br>            Id = 1,<br>            Title = &quot;Crime and Punishment&quot;,<br>            Author = &quot;Dostoevsky&quot;,<br>            Price = 12.99m,<br>            PublishedDate = new DateTime(1866, 1, 1)<br>        },<br>        new Book<br>        {<br>            Id = 2,<br>            Title = &quot;1984&quot;,<br>            Author = &quot;George Orwell&quot;,<br>            Price = 9.99m,<br>            PublishedDate = new DateTime(1949, 6, 8)<br>        },<br>        new Book<br>        {<br>            Id = 3,<br>            Title = &quot;The Little Prince&quot;,<br>            Author = &quot;Saint-Exupéry&quot;,<br>            Price = 7.50m,<br>            PublishedDate = new DateTime(1943, 4, 6)<br>        },<br>    ];<br>}</pre><h3>3. Resolvers with Dependency Injection</h3><p>In real-world applications, data lives in databases — not in-memory lists. HotChocolate v14 automatically injects registered services into resolver method parameters from the DI container.</p><h3>3.1 Domain Models and DbContext</h3><pre>// Models/Author.cs<br>public class Author<br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; } = default!;<br>    public string Country { get; set; } = default!;<br>    public List&lt;Book&gt; Books { get; set; } = new();<br>}</pre><pre>// Models/Book.cs<br>public class Book<br>{<br>    public int Id { get; set; }<br>    public string Title { get; set; } = default!;<br>    public decimal Price { get; set; }<br>    public int AuthorId { get; set; }<br>    public Author Author { get; set; } = default!;<br>    public List&lt;Review&gt; Reviews { get; set; } = new();<br>}</pre><pre>// Models/Review.cs<br>public class Review<br>{<br>    public int Id { get; set; }<br>    public string Comment { get; set; } = default!;<br>    public int Stars { get; set; } // 1 through 5<br>    public int BookId { get; set; }<br>    public Book Book { get; set; } = default!;<br>}</pre><pre>// Data/AppDbContext.cs<br>using Microsoft.EntityFrameworkCore;<br><br>public class AppDbContext : DbContext<br>{<br>    public AppDbContext(DbContextOptions&lt;AppDbContext&gt; options)<br>        : base(options) { }<br>    public DbSet&lt;Book&gt; Books =&gt; Set&lt;Book&gt;();<br>    public DbSet&lt;Author&gt; Authors =&gt; Set&lt;Author&gt;();<br>    public DbSet&lt;Review&gt; Reviews =&gt; Set&lt;Review&gt;();<br>}</pre><h3>3.2 The Resolver</h3><pre>// Types/Query.cs<br>using Microsoft.EntityFrameworkCore;<br>public class Query<br>{<br>    // In HotChocolate v14, services registered in the DI container<br>    // are automatically injected as method parameters.<br>    // The [Service] attribute from older versions is no longer required<br>    // in most scenarios.<br>    public async Task&lt;List&lt;Book&gt;&gt; GetBooks(AppDbContext dbContext)<br>        =&gt; await dbContext.Books.ToListAsync();<br>    public async Task&lt;Book?&gt; GetBookById(int id, AppDbContext dbContext)<br>        =&gt; await dbContext.Books.FindAsync(id);<br>    public async Task&lt;List&lt;Author&gt;&gt; GetAuthors(AppDbContext dbContext)<br>        =&gt; await dbContext.Authors.Include(a =&gt; a.Books).ToListAsync();<br>}</pre><h3>3.3 Program.cs Configuration</h3><pre>// Program.cs<br>var builder = WebApplication.CreateBuilder(args);<br>builder.Services.AddDbContextPool&lt;AppDbContext&gt;(options =&gt;<br>    options.UseSqlServer(<br>        builder.Configuration.GetConnectionString(&quot;Default&quot;)));<br>builder.Services<br>    .AddGraphQLServer()<br>    .AddQueryType&lt;Query&gt;()<br>    .AddTypes()                              // Auto-discover all types<br>    .AddGlobalObjectIdentification()         // ← Relay support - enables the Node interface,<br>                                             //   node()/nodes() root queries, and global IDs.<br>                                             //   Required even at this stage if you plan to use<br>                                             //   [NodeResolver] on your types (Section 6).<br>    .RegisterDbContextFactory&lt;AppDbContext&gt;(); // Inject DbContext into resolvers<br>var app = builder.Build();<br>app.MapGraphQL();<br>app.Run();</pre><blockquote><strong><em>Important:</em></strong><em> </em><em>.AddGlobalObjectIdentification() is what activates the Relay Node pattern in HotChocolate. Without this line, the </em><em>node() / </em><em>nodes() root queries won&#39;t exist in your schema and </em><em>[NodeResolver] attributes will have no effect. We add it here so that the project is Relay-ready from the start. We&#39;ll cover what it does in detail in </em><strong><em>Section 6</em></strong><em>.</em></blockquote><h3>4. Type Extension Resolvers</h3><p>Type Extensions are one of the most powerful features in HotChocolate. They let you add fields to an existing type without modifying its original class. This provides two major benefits:</p><ul><li><strong>Separation of Concerns:</strong> Your Book model stays a clean database entity; additional computed fields live in separate files.</li><li><strong>Lazy Evaluation:</strong> Extended fields only execute when the client actually requests them. If the client doesn’t ask for author, that resolver never fires.</li></ul><pre>// Types/BookResolvers.cs<br>[ExtendObjectType&lt;Book&gt;]<br>public class BookResolvers<br>{<br>    // The [Parent] attribute gives you the Book instance this<br>    // resolver is being called for.<br>    //<br>    // When the client queries { books { author { name } } },<br>    // HotChocolate first runs the books resolver to get a list of Books.<br>    // Then, for EACH Book, it calls this method.<br>    // [Parent] Book book = the current Book in the iteration.<br><br>    public async Task&lt;Author?&gt; GetAuthor(<br>        [Parent] Book book,<br>        AppDbContext dbContext)<br>    {<br>        return await dbContext.Authors.FindAsync(book.AuthorId);<br>    }<br>    // Computed field: average review rating for the book<br>    public async Task&lt;double&gt; GetAverageRating(<br>        [Parent] Book book,<br>        AppDbContext dbContext)<br>    {<br>        return await dbContext.Reviews<br>            .Where(r =&gt; r.BookId == book.Id)<br>            .AverageAsync(r =&gt; (double?)r.Stars) ?? 0;<br>    }<br>    // Computed field: total number of reviews<br>    public async Task&lt;int&gt; GetReviewCount(<br>        [Parent] Book book,<br>        AppDbContext dbContext)<br>    {<br>        return await dbContext.Reviews<br>            .CountAsync(r =&gt; r.BookId == book.Id);<br>    }<br>}</pre><p>Now the following query works:</p><pre>query {<br>  books {<br>    id<br>    title<br>    price<br>    author {<br>      name<br>      country<br>    }<br>    averageRating<br>    reviewCount<br>  }<br>}</pre><h3>5. Solving the N+1 Problem with DataLoaders</h3><h3>5.1 What Is the N+1 Problem?</h3><p>This is the single most common performance issue in GraphQL (and ORMs in general). Here is what happens:</p><ol><li>You list 10 books → <strong>1</strong> database query</li><li>For each book, you fetch its author individually → <strong>10</strong> database queries</li><li>Total: <strong>11 queries</strong> (1 + N, where N = 10)</li></ol><p>If you had 100 books, that would be 101 queries. This is unacceptable in production.</p><h3>5.2 The Solution: BatchDataLoader</h3><p>A DataLoader collects all requested IDs, waits for the current execution batch to complete, and then fires a single bulk query.</p><pre>// DataLoaders/AuthorBatchDataLoader.cs<br>public class AuthorBatchDataLoader : BatchDataLoader&lt;int, Author&gt;<br>{<br>    private readonly IDbContextFactory&lt;AppDbContext&gt; _dbContextFactory;<br>    public AuthorBatchDataLoader(<br>        IDbContextFactory&lt;AppDbContext&gt; dbContextFactory,<br>        IBatchScheduler batchScheduler,<br>        DataLoaderOptions? options = null)<br>        : base(batchScheduler, options)<br>    {<br>        _dbContextFactory = dbContextFactory;<br>    }<br>    protected override async Task&lt;IReadOnlyDictionary&lt;int, Author&gt;&gt; LoadBatchAsync(<br>        IReadOnlyList&lt;int&gt; keys,<br>        CancellationToken cancellationToken)<br>    {<br>        // Instead of 10 separate queries, ONE query is executed:<br>        // SELECT * FROM Authors WHERE Id IN (1, 2, 3, 5, 8, ...)<br>        await using var dbContext =<br>            await _dbContextFactory.CreateDbContextAsync(cancellationToken);<br>        return await dbContext.Authors<br>            .Where(a =&gt; keys.Contains(a.Id))<br>            .ToDictionaryAsync(a =&gt; a.Id, cancellationToken);<br>    }<br>}</pre><pre>// Types/BookResolvers.cs<br>[ExtendObjectType&lt;Book&gt;]<br>public class BookResolvers<br>{<br>    // DataLoader version — no more N+1!<br>    public async Task&lt;Author?&gt; GetAuthor(<br>        [Parent] Book book,<br>        AuthorBatchDataLoader authorLoader)<br>    {<br>        return await authorLoader.LoadAsync(book.AuthorId);<br>    }<br>}</pre><p><strong>Step-by-step execution:</strong></p><ol><li>GraphQL returns 10 books.</li><li>For each book, GetAuthor is called → the DataLoader buffers each authorId.</li><li>After all 10 calls are queued, LoadBatchAsync fires <strong>once</strong>.</li><li>A single SELECT ... WHERE Id IN (...) hits the database.</li><li>Results are distributed back to the corresponding books.</li></ol><p><strong>Result:</strong> 11 queries reduced to <strong>2 queries</strong> (1 for books + 1 for authors).</p><h3>6. The Relay Specification — Global Object Identification &amp; the Node Pattern</h3><h3>6.1 The Problem</h3><p>In a typical system, IDs are scoped to their own type:</p><ul><li>Book ID: 1</li><li>Author ID: 1</li><li>Review ID: 1</li></ul><p>All three are “1”, but they refer to completely different objects. If a client says “fetch the object with ID 1”, which one do you return?</p><h3>6.2 The Relay Solution: Global Object Identification</h3><p>The Relay specification requires every object to have a <strong>globally unique ID</strong>. HotChocolate achieves this by Base64-encoding the type name and the internal ID together. Here is how it translates:</p><p>Entity Internal ID Global Relay ID Decoded Book 1 1 Qm9vazox Book:1 Author 1 1 QXV0aG9yOjE= Author:1 Review 1 1 UmV2aWV3OjE= Review:1</p><p>Now every ID is unique across the entire system and carries type information within it.</p><h3>6.3 The Node Pattern</h3><p>The Relay spec defines a Node interface that every identifiable entity must implement. The interface makes a single promise: <em>&quot;I have an </em><em>id field, and you can re-fetch me using that ID.&quot;</em></p><p>This unlocks two powerful root-level queries:</p><ul><li>node(id: ID!): Node — fetch <strong>any</strong> object by its global ID.</li><li>nodes(ids: [ID!]!): [Node]! — fetch <strong>multiple</strong> objects of potentially different types in a single call.</li></ul><h3>6.4 Enabling Relay in HotChocolate v14</h3><p>If you’ve been following along from Section 3, you already have .AddGlobalObjectIdentification() in your Program.cs. Here&#39;s the full configuration for reference:</p><pre>// Program.cs<br>builder.Services<br>    .AddGraphQLServer()<br>    .AddQueryType&lt;Query&gt;()<br>    .AddMutationType&lt;Mutation&gt;()<br>    .AddTypes()<br>    .AddGlobalObjectIdentification()    // ← This is the key line!<br>                                        //   Activates the Node interface, globally unique IDs,<br>                                        //   and the node()/nodes() root queries.<br>    .RegisterDbContextFactory&lt;AppDbContext&gt;();</pre><blockquote><strong><em>What does </em></strong><strong><em>.AddGlobalObjectIdentification() actually do?</em></strong></blockquote><ol><li>Adds the Node interface to your schema.</li><li>Adds the node(id: ID!) and nodes(ids: [ID!]!) root query fields.</li><li>Converts all Id properties on types with a [NodeResolver] to Base64-encoded globally unique IDs.</li><li>Enables the gateway (Fusion) to resolve entities across subgraphs via the node() query.</li></ol><blockquote><strong><em>Without this line, </em></strong><strong><em>[NodeResolver] attributes are ignored and Relay features won&#39;t work.</em></strong></blockquote><h3>6.5 Implementing Node Resolvers</h3><p>A [NodeResolver] tells HotChocolate how to re-fetch an object when given its global Relay ID.</p><pre>// Types/BookType.cs<br>[ObjectType&lt;Book&gt;]<br>public static partial class BookType<br>{<br>    // When the gateway or a client sends &quot;Qm9vazox&quot;,<br>    // HotChocolate automatically decodes it:<br>    //   type → &quot;Book&quot;, id → 1<br>    // Then it calls this method with id = 1.<br>    [NodeResolver]<br>    public static async Task&lt;Book?&gt; GetBookById(<br>        int id,<br>        AppDbContext dbContext)<br>    {<br>        return await dbContext.Books.FindAsync(id);<br>    }<br>}</pre><pre>// Types/AuthorType.cs<br>[ObjectType&lt;Author&gt;]<br>public static partial class AuthorType<br>{<br>    [NodeResolver]<br>    public static async Task&lt;Author?&gt; GetAuthorById(<br>        int id,<br>        AppDbContext dbContext)<br>    {<br>        return await dbContext.Authors.FindAsync(id);<br>    }<br>}</pre><pre>// Types/ReviewType.cs<br>[ObjectType&lt;Review&gt;]<br>public static partial class ReviewType<br>{<br>    [NodeResolver]<br>    public static async Task&lt;Review?&gt; GetReviewById(<br>        int id,<br>        AppDbContext dbContext)<br>    {<br>        return await dbContext.Reviews.FindAsync(id);<br>    }<br>}</pre><h3>6.6 The Resulting Schema</h3><p>Once you call AddGlobalObjectIdentification() and define [NodeResolver]s, HotChocolate automatically generates this schema:</p><pre>interface Node {<br>  id: ID!<br>}<br>type Book implements Node {<br>  id: ID!          # Now returns &quot;Qm9vazox&quot; - globally unique<br>  title: String!<br>  price: Decimal!<br>  author: Author!<br>}<br>type Author implements Node {<br>  id: ID!          # Now returns &quot;QXV0aG9yOjE=&quot; - globally unique<br>  name: String!<br>  country: String!<br>  books: [Book!]!<br>}<br>type Review implements Node {<br>  id: ID!<br>  comment: String!<br>  stars: Int!<br>}<br>type Query {<br>  # Relay&#39;s magic queries - added automatically by AddGlobalObjectIdentification()<br>  node(id: ID!): Node<br>  nodes(ids: [ID!]!): [Node]!<br>  books: [Book!]!<br>  authors: [Author!]!<br>}</pre><h3>6.7 Relay Query Examples</h3><p><strong>Standard query — listing books:</strong></p><pre>query {<br>  books {<br>    id          # Returns &quot;Qm9vazox&quot; instead of plain &quot;1&quot;<br>    title<br>    price<br>  }<br>}</pre><p><strong>node() query — fetch any object by its global ID:</strong></p><pre>query {<br>  node(id: &quot;Qm9vazox&quot;) {<br>    ... on Book {<br>      title<br>      price<br>      author {<br>        name<br>      }<br>    }<br>  }<br>}</pre><p>Notice that the client does not need to know the type. The ID carries the type information. HotChocolate decodes Qm9vazox → Book:1 and routes to the BookType&#39;s [NodeResolver].</p><p><strong>nodes() query — fetch different types in a single call:</strong></p><pre>query {<br>  nodes(ids: [&quot;Qm9vazox&quot;, &quot;QXV0aG9yOjE=&quot;, &quot;UmV2aWV3OjM=&quot;]) {<br>    ... on Book {<br>      title<br>    }<br>    ... on Author {<br>      name<br>    }<br>    ... on Review {<br>      comment<br>      stars<br>    }<br>  }<br>}</pre><p>Three different types fetched in a single round-trip!</p><h3>6.8 Using Global IDs in Mutations</h3><p>Use the [ID] attribute to accept global Relay IDs in input arguments and have them automatically decoded to native integers:</p><pre>// Types/Mutation.cs<br>public class Mutation<br>{<br>    // [ID&lt;Book&gt;] → Client sends &quot;Qm9vazox&quot;, method receives int 1<br>    public async Task&lt;Book?&gt; UpdateBookPrice(<br>        [ID&lt;Book&gt;] int id,<br>        decimal newPrice,<br>        AppDbContext dbContext)<br>    {<br>        var book = await dbContext.Books.FindAsync(id);<br>        if (book is null) return null;<br>        book.Price = newPrice;<br>        await dbContext.SaveChangesAsync();<br>        return book;<br>    }<br>    // Works with arrays too<br>    public async Task&lt;List&lt;Book&gt;&gt; GetBooksByIds(<br>        [ID&lt;Book&gt;] int[] ids,<br>        AppDbContext dbContext)<br>    {<br>        return await dbContext.Books<br>            .Where(b =&gt; ids.Contains(b.Id))<br>            .ToListAsync();<br>    }<br>}</pre><p>In input types:</p><pre>// Types/AddReviewInput.cs<br>public record AddReviewInput(<br>    [property: ID&lt;Book&gt;] int BookId,   // Client sends global ID → decoded to int<br>    string Comment,<br>    int Stars);</pre><h3>7. Fusion — Distributed GraphQL Gateway</h3><h3>7.1 What Is Fusion?</h3><p>Fusion is HotChocolate’s approach to distributed GraphQL. It composes multiple independent GraphQL services (called <strong>subgraphs</strong>) behind a single gateway that exposes one unified schema to the client.</p><pre>Client<br>          │<br>          ▼<br>    ┌───────────────┐<br>    │    GATEWAY    │  ← Single GraphQL endpoint<br>    │   (Fusion)    │<br>    └──┬────┬────┬──┘<br>       │    │    │<br>       ▼    ▼    ▼<br>    ┌────┐┌────┐┌────┐<br>    │ A  ││ B  ││ C  │  ← Subgraphs (independent services)<br>    └────┘└────┘└────┘<br>   Books Authors Reviews</pre><p><strong>Key benefits:</strong></p><ul><li>Each service is independently deployable.</li><li>Each service can have its own database and tech stack.</li><li>Different teams can own different subgraphs.</li><li>The client sees one schema, one endpoint — zero awareness of the underlying complexity.</li></ul><h3>7.2 Why Relay Is Mandatory for Fusion</h3><p><strong>Fusion cannot function without Relay (Global Object Identification).</strong></p><p>Here is why. The gateway must stitch data across subgraphs. Consider this scenario:</p><ol><li>The client asks: <em>“Give me all books with their authors.”</em></li><li>The Book entity lives in BookService, the Author entity lives in AuthorService.</li><li>The gateway fetches books from BookService — each book has an authorId.</li><li>The gateway converts that authorId to a Relay global ID and sends a node() query to AuthorService.</li><li>AuthorService’s [NodeResolver] returns the Author object.</li><li>The gateway merges the results and returns them to the client.</li></ol><p>Without Relay, the gateway has no standardized mechanism to resolve cross-service references.</p><h3>7.3 Project Structure</h3><pre>📁 Solution/<br>├── 📁 src/<br>│   ├── 📁 BookService/          ← Subgraph 1 (port 5001)<br>│   │   ├── Program.cs<br>│   │   ├── Models/<br>│   │   ├── Data/<br>│   │   ├── Types/<br>│   │   └── BookService.csproj<br>│   ├── 📁 AuthorService/        ← Subgraph 2 (port 5002)<br>│   │   ├── Program.cs<br>│   │   ├── Models/<br>│   │   ├── Data/<br>│   │   ├── Types/<br>│   │   └── AuthorService.csproj<br>│   ├── 📁 ReviewService/        ← Subgraph 3 (port 5003)<br>│   │   ├── Program.cs<br>│   │   ├── Models/<br>│   │   ├── Data/<br>│   │   ├── Types/<br>│   │   └── ReviewService.csproj<br>│   └── 📁 Gateway/              ← Fusion Gateway (port 5000)<br>│       ├── Program.cs<br>│       └── Gateway.csproj</pre><h3>7.4 Subgraph 1: BookService</h3><p><strong>Project file:</strong></p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;<br>  &lt;PropertyGroup&gt;<br>    &lt;TargetFramework&gt;net8.0&lt;/TargetFramework&gt;<br>  &lt;/PropertyGroup&gt;<br>  &lt;ItemGroup&gt;<br>    &lt;PackageReference Include=&quot;HotChocolate.AspNetCore&quot; Version=&quot;14.*&quot; /&gt;<br>    &lt;PackageReference Include=&quot;HotChocolate.Fusion.AspNetCore&quot; Version=&quot;14.*&quot; /&gt;<br>    &lt;PackageReference Include=&quot;Microsoft.EntityFrameworkCore.SqlServer&quot; Version=&quot;8.*&quot; /&gt;<br>  &lt;/ItemGroup&gt;<br>&lt;/Project&gt;</pre><p><strong>Model:</strong></p><pre>// src/BookService/Models/Book.cs<br>namespace BookService.Models;<br><br>public class Book<br>{<br>    public int Id { get; set; }<br>    public string Title { get; set; } = default!;<br>    public string Isbn { get; set; } = default!;<br>    public decimal Price { get; set; }<br>    public int AuthorId { get; set; }          // Foreign key - but Author does NOT live here<br>    public DateTime PublishedDate { get; set; }<br>}</pre><p><strong>Program.cs (BookService):</strong></p><pre>// src/BookService/Program.cs<br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddDbContextPool&lt;BookDbContext&gt;(options =&gt;<br>    options.UseSqlServer(<br>        builder.Configuration.GetConnectionString(&quot;Default&quot;)));<br>builder.Services<br>    .AddGraphQLServer()<br>    .AddQueryType&lt;Query&gt;()<br>    .AddTypes()<br>    .AddGlobalObjectIdentification()          // ← Required! Every subgraph must enable Relay<br>                                              //   so the Fusion gateway can resolve entities<br>                                              //   via node()/nodes() queries.<br>    .RegisterDbContextFactory&lt;BookDbContext&gt;();<br>var app = builder.Build();<br>app.MapGraphQL();<br>app.Run();</pre><blockquote><strong><em>Critical:</em></strong><em> Every subgraph in a Fusion architecture </em><strong><em>must</em></strong><em> include </em><em>.AddGlobalObjectIdentification(). This is what allows the gateway to send </em><em>node() and </em><em>nodes() queries to resolve cross-service references. Without it, the gateway cannot stitch data across services.</em></blockquote><p><strong>Author Stub — the cross-service reference:</strong></p><p>This is a critical piece. BookService does not know what an Author looks like — it only stores an authorId. But for Fusion to stitch the two services together, BookService must provide a minimal reference to the Author type.</p><pre>// src/BookService/Types/AuthorNode.cs<br>using BookService.Data;<br>using BookService.Models;<br>using Microsoft.EntityFrameworkCore;<br><br>namespace BookService.Types;<br>// This is a &quot;stub&quot; representing the Author entity from AuthorService.<br>// It carries nothing but an Id.<br>// The Fusion gateway matches this stub against the real Author<br>// from AuthorService during composition.<br>public class Author<br>{<br>    public int Id { get; set; }<br>}<br>[ExtendObjectType(&quot;Author&quot;)]<br>public static class AuthorNode<br>{<br>    // Adds a &quot;books&quot; field to the Author type.<br>    // When someone queries an Author&#39;s books, this resolver runs<br>    // in BookService&#39;s database context.<br>    public static async Task&lt;List&lt;Book&gt;&gt; GetBooks(<br>        [Parent] Author author,<br>        BookDbContext dbContext)<br>    {<br>        return await dbContext.Books<br>            .Where(b =&gt; b.AuthorId == author.Id)<br>            .ToListAsync();<br>    }<br>}</pre><h3>7.5 Subgraph 2: AuthorService</h3><p>AuthorService follows a similar pattern to BookService, exposing its own Data, Query, and AuthorType with a [NodeResolver].</p><blockquote><strong><em>Remember:</em></strong><em> AuthorService’s </em><em>Program.cs must also include </em><em>.AddGlobalObjectIdentification() — just like BookService.</em></blockquote><h3>7.6 Subgraph 3: ReviewService</h3><p><strong>Program.cs (ReviewService):</strong></p><pre>// src/ReviewService/Program.cs<br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddDbContextPool&lt;ReviewDbContext&gt;(options =&gt;<br>    options.UseSqlServer(<br>        builder.Configuration.GetConnectionString(&quot;Default&quot;)));<br>builder.Services<br>    .AddGraphQLServer()<br>    .AddQueryType&lt;Query&gt;()<br>    .AddTypes()<br>    .AddGlobalObjectIdentification()          // ← Required for every subgraph!<br>    .RegisterDbContextFactory&lt;ReviewDbContext&gt;();<br>var app = builder.Build();<br>app.MapGraphQL();<br>app.Run();</pre><p><strong>Book Stub — cross-service reference:</strong></p><pre>// src/ReviewService/Types/BookNode.cs<br>using Microsoft.EntityFrameworkCore;<br>using ReviewService.Data;<br>using ReviewService.Models;<br><br>namespace ReviewService.Types;<br>// Minimal reference representing the Book entity from BookService.<br>public class Book<br>{<br>    public int Id { get; set; }<br>}<br>[ExtendObjectType(&quot;Book&quot;)]<br>public static class BookNode<br>{<br>    // Adds a &quot;reviews&quot; field to the Book type<br>    public static async Task&lt;List&lt;Review&gt;&gt; GetReviews(<br>        [Parent] Book book,<br>        ReviewDbContext dbContext)<br>    {<br>        return await dbContext.Reviews<br>            .Where(r =&gt; r.BookId == book.Id)<br>            .OrderByDescending(r =&gt; r.CreatedAt)<br>            .ToListAsync();<br>    }<br>}</pre><h3>7.7 The Gateway</h3><pre>// src/Gateway/Program.cs<br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services<br>    .AddFusionGatewayServer()<br>    .ConfigureFromFile(&quot;./gateway.fgp&quot;);    // Composition config file<br>    // Alternative: .ConfigureFromCloud()   // With ChilliCream Barista<br>var app = builder.Build();<br>app.MapGraphQL();                            // Single endpoint: /graphql<br>app.Run();</pre><h3>7.8 Schema Composition with the CLI</h3><p>Compose all subgraphs into the gateway config:</p><pre>hc fusion compose \<br>  -p ./src/Gateway/gateway.fgp \<br>  -s ./src/BookService \<br>  -s ./src/AuthorService \<br>  -s ./src/ReviewService</pre><h3>7.9 Querying Through the Gateway — Where the Magic Happens</h3><p>The client sends all queries to a single endpoint. The gateway automatically decomposes the query and routes each part to the appropriate subgraph.</p><pre># This SINGLE query pulls data from 3 DIFFERENT services!<br>query {<br>  books {<br>    # ↓ Resolved by BookService<br>    id<br>    title<br>    isbn<br>    price<br>    # ↓ Resolved by AuthorService (via Relay node resolution)<br>    author {<br>      name<br>      country<br>    }<br>    # ↓ Resolved by ReviewService<br>    reviews {<br>      comment<br>      stars<br>    }<br>  }<br>}</pre><h3>8. How Node Resolution Works Inside the Fusion Gateway</h3><p>When a client sends books { title author { name } reviews { comment } }, here is the step-by-step breakdown of what happens inside the gateway:</p><pre>┌────────────────────────────────────────────────────────────┐<br>│                     CLIENT QUERY                           │<br>│                                                            │<br>│  query {                                                   │<br>│    books {                                                 │<br>│      title          ← from BookService                     │<br>│      author {                                              │<br>│        name         ← from AuthorService                   │<br>│      }                                                     │<br>│      reviews {                                             │<br>│        comment      ← from ReviewService                   │<br>│      }                                                     │<br>│    }                                                       │<br>│  }                                                         │<br>└──────────────────────┬─────────────────────────────────────┘<br>                       │<br>                       ▼<br>┌────────────────────────────────────────────────────────────┐<br>│                    FUSION GATEWAY                          │<br>│                                                            │<br>│  Step 1 — Query Planning:                                  │<br>│    Analyze the query. Which field belongs to which service?│<br>│    • title, isbn, price      → BookService                 │<br>│    • author.name, author.bio → AuthorService               │<br>│    • reviews.comment, stars  → ReviewService               │<br>│                                                            │<br>│  Step 2 — Fetch from BookService:                          │<br>│    query { books { id title authorId } }                   │<br>│    Result: [                                               │<br>│      { id: &quot;Qm9vazox&quot;, title: &quot;Crime&quot;, authorId: 1 },      │<br>│      { id: &quot;Qm9vazoy&quot;, title: &quot;1984&quot;, authorId: 2 }        │<br>│    ]                                                       │<br>│                                                            │<br>│  Step 3 — Parallel fan-out:                                │<br>│                                                            │<br>│    a) AuthorService ← Relay node/nodes query:              │<br>│       query {                                              │<br>│         nodes(ids: [&quot;QXV0aG9yOjE=&quot;, &quot;QXV0aG9yOjI=&quot;]) {     │<br>│           ... on Author { name country }                   │<br>│         }                                                  │<br>│       }                                                    │<br>│                                                            │<br>│    b) ReviewService ← Book reference resolution:           │<br>│       Fetches reviews for each book ID                     │<br>│                                                            │<br>│  Step 4 — Merge:                                           │<br>│    Combine all results into a single response.             │<br>│    Return the unified result to the client.                │<br>└────────────────────────────────────────────────────────────┘</pre><p><strong>Key observations:</strong></p><ul><li>Steps 3a and 3b run <strong>in parallel</strong> — maximum performance.</li><li>The gateway converts authorId into a Relay global ID and sends a nodes() query to AuthorService. <strong>This is why Relay is mandatory.</strong></li><li>The client is completely unaware of any of this. It sees one schema, one endpoint.</li></ul><h3>Summary: The .AddGlobalObjectIdentification() Checklist</h3><p>To make sure Relay and Fusion work correctly, verify these points:</p><ol><li><strong>Every </strong><strong>Program.cs</strong> (both standalone apps and subgraphs) must call .AddGlobalObjectIdentification() on the GraphQL server builder.</li><li><strong>Every entity</strong> that needs to be fetched by global ID must have a type class with a [NodeResolver] method.</li><li><strong>Subgraph stubs</strong> (like Author in BookService or Book in ReviewService) must have an Id property so the gateway can create global IDs for cross-service resolution.</li><li><strong>Mutations</strong> accepting global IDs should use the [ID&lt;T&gt;] attribute to auto-decode them.</li></ol><p>Without .AddGlobalObjectIdentification(), none of the Relay features activate — the node()/nodes() queries won&#39;t exist, IDs will remain plain integers, and Fusion cross-service resolution will fail.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fcb87edac19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Federating .NET GraphQL APIs Locally: A Fusion Guide for Schema Stitching]]></title>
            <link>https://medium.com/@umithavare/federating-net-graphql-apis-locally-a-fusion-guide-for-schema-stitching-bb0a6495819c?source=rss-22f7fc910579------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb0a6495819c</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[stitching]]></category>
            <category><![CDATA[fusion]]></category>
            <category><![CDATA[graphql-schema]]></category>
            <dc:creator><![CDATA[Ümit Havare]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 12:53:16 GMT</pubDate>
            <atom:updated>2025-12-02T11:38:55.265Z</atom:updated>
            <content:encoded><![CDATA[<h3>Modernizing .NET GraphQL: Federating APIs Locally from Legacy Stitching to Fusion Composition</h3><p>In the modern landscape of software architecture, <strong>Microservices</strong> have become the de facto standard for building scalable applications. However, orchestrating these distributed services — especially during the <strong>Local Development</strong> phase — can often feel overwhelming.</p><p>If you’ve ever struggled with network isolation issues, port conflicts, or the complexity of configuring a gateway to talk to services running on localhost, this guide is for you.</p><p>We will walk through the <strong>“Manual Composition”</strong> process using <strong>ChilliCream Fusion v14</strong>. We will bypass the complexity of cloud deployments and Kubernetes pods to give you a pure, CLI-driven federation experience right on your local machine.</p><h3>Understanding GraphQL Fusion</h3><p>Before diving into code, let’s clarify the core concept.</p><p>Imagine you have a monolithic API that does everything, but it’s heavy and hard to modify. You decide to break it down into specialized services: an Identity Service and an Ordering Service.</p><p><strong>Fusion</strong> is the infrastructure that connects these tools back together. To the user (your frontend app), it still looks and feels like a single API, even though it’s composed of separate, independent pieces.</p><p><em>Figure 1: The Fusion Architecture. Notice how the Gateway aggregates types from independent services (Users, Products, Orders) into a single, cohesive API.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*v4s5Vuqvz2YfPSCBtCZCWg.png" /></figure><p><strong>Key Benefits:</strong></p><ol><li><strong>Unified API:</strong> Your frontend communicates with a single endpoint, regardless of the number of backend services.</li><li><strong>Autonomy:</strong> Teams can work on different services independently without blocking each other.</li><li><strong>Performance:</strong> Fusion plans the most efficient route to fetch data from multiple services in parallel.</li></ol><h3>The Concept of “Composition”</h3><p>In Fusion, <strong>Composition</strong> is the critical step where individual service schemas are merged. Think of your microservices as separate <strong>Puzzle Pieces</strong>.</p><ul><li>The Identity Service has a piece that looks like a User.</li><li>The Ordering Service has a piece that looks like an Order.</li></ul><p>If you simply run these services together (Runtime Stitching), integration issues might occur. <strong>Composition</strong> is the process of assembling the puzzle ahead of time to ensure every piece fits perfectly.</p><ol><li><strong>Pack:</strong> Capture the schema shape of each service.</li><li><strong>Compose:</strong> Merge them into a single Gateway configuration.</li><li><strong>Result:</strong> A valid “Map” (.fgp file) or build-time errors if there are conflicts.</li></ol><p>This guide focuses on performing this “Puzzle Assembly” manually on your local machine.</p><h3>Evolution: Fusion vs. Schema Stitching</h3><p>If you are coming from Schema Stitching, it’s important to understand the difference. To appreciate Fusion, let’s look at how we used to solve this.</p><h3>Method 1: The Legacy Way (Schema Stitching)</h3><p>In the old approach, the services were unaware of each other. We had to write manual “glue code” on the Gateway.</p><p><strong>Gateway Config:</strong></p><pre>// Program.cs<br>builder.Services.AddRemoteSchema(&quot;Identity&quot;);<br>builder.Services.AddRemoteSchema(&quot;Ordering&quot;);<br>builder.Services.AddTypeExtensionsFromFile(&quot;./stitching.graphql&quot;);</pre><p><strong>Stitching File (</strong><strong>stitching.graphql):</strong></p><pre>extend type Order {<br>    # Manual directive to fetch data<br>    buyer: User @delegate(schema: &quot;Identity&quot;, path: &quot;userById(id: $fields:buyerId)&quot;)<br>}</pre><p><strong>The Problem:</strong> This was brittle. If the Identity service changed, the Gateway broke at runtime.</p><h3>Method 2: The Modern Way (Fusion)</h3><p>Fusion uses an <strong>entity-based</strong> approach. You define “Entities” (like User) and &quot;Keys&quot; (like id). You tell Fusion, <em>&quot;This is a User, and here is how you identify it.&quot;</em> Fusion then acts as a GPS, automatically finding the efficient route based on the provided map.</p><h3>The Problem: Managing Distributed State Locally</h3><p>Consider a distributed e-commerce platform with two distinct services:</p><ol><li><strong>Identity Service:</strong> The source of truth for user data (Users, Roles).</li><li><strong>Ordering Service:</strong> Manages transactional data (Orders, Payments).</li></ol><p>The Ordering Service knows <em>who</em> bought an item only by a BuyerId. However, the frontend requires a unified response: <em>&quot;Order details expanded with the buyer&#39;s full profile.&quot;</em></p><p>In a monolithic world, this is a SQL JOIN. In a distributed world, it’s a network call. In a Federated world, it’s the job of the Gateway to merge these two graphs.</p><p><strong>Local Development Challenge:</strong> When running locally, the Gateway needs a configuration map to locate Identity and Ordering services and understand how to link them.</p><h3>Prerequisites: Environment Setup</h3><p>We will rely on the Fusion Command Line Interface (CLI) for schema composition. Open your terminal and install the Fusion CLI globally:</p><pre>dotnet tool install -g HotChocolate.Fusion.CommandLine</pre><p><em>Verification:</em> Run fusion --help to ensure the installation was successful.</p><h3>Scenario Implementation</h3><p>We will simulate a scenario with two decoupled services running on specific local ports:</p><ul><li><strong>Identity API:</strong> <a href="http://localhost:5001/graphql">http://localhost:5001/graphql</a></li><li><strong>Ordering API:</strong> <a href="http://localhost:5002/graphql">http://localhost:5002/graphql</a></li><li><strong>Gateway:</strong> <a href="http://localhost:5000/graphql">http://localhost:5000/graphql</a></li></ul><h3>Step 1: Subgraph Configuration</h3><p>Fusion requires a subgraph-config.json file in the root of each service. This file registers the service name and address.</p><p><strong>Identity Service Configuration:</strong> Create subgraph-config.json in the Identity project root:</p><pre>{<br>  &quot;subgraph&quot;: &quot;Identity&quot;,<br>  &quot;http&quot;: { &quot;baseAddress&quot;: &quot;http://localhost:5001/graphql&quot; }<br>}</pre><p><strong>Ordering Service Configuration:</strong> Create subgraph-config.json in the Ordering project root:</p><pre>{<br>  &quot;subgraph&quot;: &quot;Ordering&quot;,<br>  &quot;http&quot;: { &quot;baseAddress&quot;: &quot;http://localhost:5002/graphql&quot; }<br>}</pre><blockquote><strong><em>Note:</em></strong><em> The </em><em>subgraph name defined here is case-sensitive and is used for referencing services during composition.</em></blockquote><h3>Step 2: Defining Schema Extensions</h3><p>We need to define how services interact without adding hard dependencies in the C# code. This is done using Schema Extensions (.graphql files).</p><p>Here, you have <strong>two options</strong>. You can choose the one that fits your architecture best.</p><h4>Option A: Consumer-Driven (Standard)</h4><p>The Ordering service (Consumer) explicitly declares what it needs from Identity.</p><p><strong>Identity (Provider):</strong></p><pre># identity.ext.graphql<br>extend type Query {<br>  userById(id: Int! @is(field: &quot;id&quot;)): User @lookup<br>}<br>extend type User @key(fields: &quot;id&quot;) { id: Int! @external }</pre><p><strong>Ordering (Consumer):</strong></p><pre># ordering.ext.graphql<br>extend type Order {<br>    buyer: User @resolve(subgraph: &quot;Identity&quot;, select: &quot;userById(id: $buyerId)&quot;)<br>}</pre><h4>Option B: Provider-Driven (Cleaner Consumer)</h4><p>This is the <strong>advanced method</strong> (and the one used in robust systems). The Ordering service remains completely clean. The Identity service proactively attaches itself to the Order type.</p><p><strong>Ordering (Consumer):</strong> Do nothing! No extension file needed.</p><p><strong>Identity (Provider — </strong><strong>identity.ext.graphql):</strong></p><pre># 1. Standard Lookup<br>extend type Query {<br>  userById(id: Int! @is(field: &quot;id&quot;)): User @lookup<br>}<br>extend type User @key(fields: &quot;id&quot;) { id: Int! @external }<br><br># 2. Stub for Order<br>type Order { buyerId: Int! }<br><br># 3. Extend Order HERE (In the Identity project)<br>extend type Order {<br>    buyer: User @resolve(subgraph: &quot;Identity&quot;, select: &quot;userById(id: $buyerId)&quot;)<br>}</pre><p><em>We will proceed assuming you chose Option A or B. The packing step handles both.</em></p><h3>Step 3: Packing Subgraphs</h3><p>We use the Fusion CLI to package our schemas. This step validates the schema and prepares it for composition.</p><p>First, export the raw schemas:</p><pre>dotnet run --project &quot;./IdentityApi&quot; -- schema export --output schema.graphql<br>dotnet run --project &quot;./OrderingApi&quot; -- schema export --output schema.graphql</pre><p>Next, use the fusion subgraph pack command.</p><p><strong>Pack Identity:</strong></p><pre>fusion subgraph pack -w &quot;./IdentityApi&quot; --schema schema.graphql --extension identity.ext.graphql</pre><p><strong>Pack Ordering:</strong> <em>If you chose Option A:</em></p><pre>fusion subgraph pack -w &quot;./OrderingApi&quot; --schema schema.graphql --extension ordering.ext.graphql</pre><p><em>If you chose Option B (Provider-Driven):</em></p><pre>fusion subgraph pack -w &quot;./OrderingApi&quot; --schema schema.graphql<br># No extension needed for Ordering in this method!</pre><p><strong>CLI Command Breakdown:</strong></p><ul><li>-w: Working directory.</li><li>--schema: Points to the exported schema file.</li><li>--extension: Points to extension files.</li></ul><h3>Step 4: Composing the Gateway</h3><p>The <strong>Composer</strong> merges individual .fsp packages into a single Gateway configuration file (.fgp).</p><p>Run this in your Gateway project directory:</p><pre>fusion compose -p gateway.fgp -s &quot;../IdentityApi/Identity.fsp&quot; -s &quot;../OrderingApi/Ordering.fsp&quot;</pre><p><strong>CLI Command Breakdown:</strong></p><ul><li>-p: Output path (gateway.fgp).</li><li>-s: Subgraph package path.</li><li>--enable-nodes: Enables Global Object Identification support.</li></ul><h3>Step 5: Running the Gateway</h3><p>Finally, configure the Gateway application to use the composed file.</p><p><strong>Program.cs in Gateway Project:</strong></p><pre>var builder = WebApplication.CreateBuilder(args);</pre><pre>builder.Services<br>    .AddFusionGatewayServer()<br>    .ConfigureFromFile(&quot;./gateway.fgp&quot;, watchFileForUpdates: true); </pre><pre>var app = builder.Build();<br>app.MapGraphQL();<br>app.Run();</pre><h3>Common Pitfalls and Solutions</h3><p>Here are common issues developers face during this process:</p><h3>1. “Unknown Directive” Error on Startup</h3><p>Symptom: API crashes with Unknown directive @resolve or Unable to find type @key.</p><p>Cause: Adding .AddDocumentFromFile(“ordering.ext.graphql”) in the C# Program.cs.</p><p>Fix: Remove references to .ext.graphql files from your C# code. These are strictly for the CLI pack process.</p><h3>2. File Locking Issues</h3><p>Symptom: The process cannot access the file ‘…apphost.exe’ because it is being used by another process.</p><p>Cause: The Gateway process is still running during a rebuild.</p><p>Fix:</p><ul><li>Stop the running application.</li><li>Run taskkill /F /IM MyGateway.exe in the terminal.</li><li>Run dotnet clean followed by dotnet run.</li></ul><h3>3. Naming Mismatches</h3><p>Symptom: Composition succeeds, but fields resolve to null.</p><p>Cause: The name in subgraph-config.json (e.g., “Identity”) does not match the name used in @resolve(subgraph: “Identity”, …) inside the extension file. Ensure these match exactly.</p><h3>Verifying the Setup</h3><p>Start all three services and navigate to http://localhost:5000/graphql. Run the following query:</p><pre>query {<br>  orders {<br>    id<br>    description<br>    buyer {<br>      username # Fetched from Identity Service<br>      email<br>    }<br>  }<br>}</pre><p>If the response contains data from both services merged into a single JSON object, the local composition is successful.</p><h3>References</h3><p>For further reading and official documentation on ChilliCream Fusion v14, please refer to the following resources:</p><ul><li><strong>Fusion Quick Start Guide: </strong><a href="https://chillicream.com/docs/fusion/v14/quick-start">https://chillicream.com/docs/fusion/v14/quick-start</a></li><li><strong>Fusion CLI Documentation:</strong> <a href="https://chillicream.com/docs/fusion/v14/cli">https://chillicream.com/docs/fusion/v14/cli</a></li><li><strong>Fusion Overview:</strong> <a href="https://chillicream.com/docs/fusion/v14">https://chillicream.com/docs/fusion/v14</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb0a6495819c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring PocketBase: The Lightweight and Open-Source Backend Solution for Modern Applications]]></title>
            <link>https://medium.com/@umithavare/exploring-pocketbase-the-lightweight-and-open-source-backend-solution-for-modern-applications-1a4512b18743?source=rss-22f7fc910579------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a4512b18743</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pocketbase]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Ümit Havare]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 22:13:50 GMT</pubDate>
            <atom:updated>2024-08-01T22:13:50.002Z</atom:updated>
            <content:encoded><![CDATA[<p>In the ever-evolving landscape of web development, developers are constantly on the lookout for tools that simplify their workflow while providing robust functionality. PocketBase emerges as a noteworthy solution in this quest, offering a lightweight, open-source backend tailored for modern applications. This article delves deep into the features, benefits, and use cases of PocketBase, providing a comprehensive guide to understanding and utilizing this exciting technology.</p><h3>What is PocketBase?</h3><p>PocketBase is an open-source backend solution that serves as a complete package for developing modern web applications. It combines several essential features, such as a database, authentication, and file storage, all packed into a lightweight server. The primary goal of PocketBase is to simplify backend development, enabling developers to focus more on building the frontend while relying on a robust backend infrastructure.</p><ol><li><strong>Built-in Database</strong>: PocketBase offers an integrated NoSQL database, which allows developers to store and manage data efficiently. It supports dynamic collections and fields, providing the flexibility to handle various data types.</li><li><strong>User Authentication</strong>: The authentication system in PocketBase is straightforward yet powerful. It supports email/password login, OAuth2 integrations (like Google, Facebook, etc.), and more. This feature ensures that user management and authentication are secure and easy to implement.</li><li><strong>File Storage</strong>: PocketBase includes file storage capabilities, enabling developers to handle file uploads and management effortlessly. This feature is particularly useful for applications that require media storage, such as image hosting or file-sharing platforms.</li><li><strong>Real-time Capabilities</strong>: PocketBase supports real-time updates, allowing applications to provide a seamless and interactive user experience. This feature is crucial for applications like chat apps or collaborative tools, where immediate feedback is essential.</li><li><strong>RESTful API</strong>: PocketBase exposes a RESTful API for interacting with the backend. This API allows developers to perform CRUD operations (Create, Read, Update, Delete) on the data, manage authentication, and handle file uploads.</li><li><strong>Lightweight and Portable</strong>: One of the standout features of PocketBase is its lightweight nature. It is designed to be easily deployable on various platforms, including cloud services, local machines, and even on Raspberry Pi devices.</li></ol><h3>Getting Started with PocketBase</h3><p>Getting started with PocketBase is straightforward, thanks to its minimal setup requirements. Here’s a step-by-step guide to help you kickstart your journey with PocketBase:</p><h4>Step 1: Installation</h4><p>PocketBase can be downloaded from its official website or GitHub repository. The following commands demonstrate how to install PocketBase on a local machine:</p><pre># Download the PocketBase binary<br>curl -O https://github.com/pocketbase/pocketbase/releases/download/v0.6.0/pocketbase_0.6.0_linux_amd64.zip<br><br># Extract the downloaded zip file<br>unzip pocketbase_0.6.0_linux_amd64.zip<br><br># Make the PocketBase binary executable<br>chmod +x pocketbase<br><br># Run the PocketBase server<br>./pocketbase serve</pre><p>After running these commands, the PocketBase server will be up and running on <a href="http://localhost:8090.">http://localhost:8090.</a></p><h4>Step 2: Setting Up Your First Project</h4><p>Once the server is running, you can access the PocketBase admin dashboard by navigating to http://localhost:8090/_/ in your web browser. The dashboard provides an intuitive interface for managing collections, users, and files.</p><ol><li><strong>Create a Collection</strong>: In PocketBase, data is organized into collections. To create a new collection, go to the “Collections” section and click “Create Collection.” Define the collection name and add fields to store data.</li><li><strong>Add Authentication</strong>: Navigate to the “Users” section to enable user authentication. PocketBase allows you to customize authentication settings, including email verification, password policies, and OAuth2 integrations.</li><li><strong>File Storage</strong>: In the “Files” section, you can manage file storage settings and monitor uploaded files. PocketBase supports image resizing, file size limits, and more.</li></ol><h4>Step 3: Integrating PocketBase with Your Application</h4><p>Integrating PocketBase with your application involves using its RESTful API to interact with the backend. Here’s a basic example of how to perform CRUD operations using the PocketBase API:</p><pre>// Import Axios or any HTTP client of your choice<br>import axios from &#39;axios&#39;;<br><br>// Set the base URL for the PocketBase API<br>const apiBaseUrl = &#39;http://localhost:8090/api&#39;;<br><br>// Example: Create a new record in a collection<br>async function createRecord(collectionName, data) {<br>  try {<br>    const response = await axios.post(`${apiBaseUrl}/collections/${collectionName}/records`, data);<br>    console.log(&#39;Record created:&#39;, response.data);<br>  } catch (error) {<br>    console.error(&#39;Error creating record:&#39;, error);<br>  }<br>}<br><br>// Example: Retrieve records from a collection<br>async function getRecords(collectionName) {<br>  try {<br>    const response = await axios.get(`${apiBaseUrl}/collections/${collectionName}/records`);<br>    console.log(&#39;Records retrieved:&#39;, response.data);<br>  } catch (error) {<br>    console.error(&#39;Error retrieving records:&#39;, error);<br>  }<br>}<br><br>// Example: Update a record in a collection<br>async function updateRecord(collectionName, recordId, data) {<br>  try {<br>    const response = await axios.patch(`${apiBaseUrl}/collections/${collectionName}/records/${recordId}`, data);<br>    console.log(&#39;Record updated:&#39;, response.data);<br>  } catch (error) {<br>    console.error(&#39;Error updating record:&#39;, error);<br>  }<br>}<br><br>// Example: Delete a record from a collection<br>async function deleteRecord(collectionName, recordId) {<br>  try {<br>    await axios.delete(`${apiBaseUrl}/collections/${collectionName}/records/${recordId}`);<br>    console.log(&#39;Record deleted&#39;);<br>  } catch (error) {<br>    console.error(&#39;Error deleting record:&#39;, error);<br>  }<br>}</pre><h3>Advantages of Using PocketBase</h3><ol><li><strong>Simplicity</strong>: PocketBase simplifies backend development by providing a ready-to-use solution with minimal configuration. Developers can focus more on frontend development and user experience.</li><li><strong>Open Source</strong>: As an open-source project, PocketBase allows developers to contribute to its development and customize it to meet their specific needs. This flexibility is a significant advantage for developers who require custom solutions.</li><li><strong>Community Support</strong>: PocketBase has an active community of developers who contribute plugins, tutorials, and support for the platform. This community-driven approach ensures that the platform continues to evolve and improve over time.</li><li><strong>Scalability</strong>: Despite its lightweight nature, PocketBase is designed to scale with your application’s needs. Whether you’re building a small personal project or a large-scale enterprise application, PocketBase can handle the load.</li><li><strong>Cross-Platform Deployment</strong>: PocketBase can be deployed on various platforms, including cloud services like AWS, Google Cloud, and Microsoft Azure. Its portability ensures that developers can choose the deployment environment that best suits their requirements.</li></ol><h3>Use Cases for PocketBase</h3><p>PocketBase is versatile and can be used in a wide range of applications. Here are some common use cases:</p><ul><li><strong>Content Management Systems (CMS)</strong>: PocketBase can be used as a backend for CMS applications, providing a user-friendly interface for managing content and media.</li><li><strong>E-commerce Platforms</strong>: With its built-in database and authentication features, PocketBase is suitable for building e-commerce platforms that require secure user authentication and data management.</li><li><strong>Social Media Applications</strong>: PocketBase’s real-time capabilities make it an excellent choice for social media applications that require instant updates and user interactions.</li><li><strong>IoT Applications</strong>: The lightweight nature of PocketBase makes it ideal for IoT applications, where resource constraints and efficiency are critical.</li></ul><h3>Challenges and Considerations</h3><p>While PocketBase offers numerous benefits, it’s essential to consider some potential challenges:</p><ul><li><strong>Limited Features Compared to Full-Fledged Solutions</strong>: PocketBase, being lightweight, may not offer all the advanced features of more extensive backend solutions. Developers should evaluate if PocketBase meets their specific requirements.</li><li><strong>Community and Ecosystem</strong>: Although PocketBase has a growing community, it may not be as extensive as other established backend solutions. Developers may need to rely on self-help or contribute to the community for specific use cases.</li></ul><h3>Conclusion</h3><p>PocketBase is a promising backend solution that caters to modern web applications’ needs. Its simplicity, lightweight nature, and comprehensive feature set make it an attractive choice for developers seeking a reliable and efficient backend solution. Whether you’re building a small-scale project or a large enterprise application, PocketBase offers the flexibility and scalability needed to bring your vision to life.</p><h3>References</h3><ul><li><strong>PocketBase Official Website:</strong> <a href="https://pocketbase.io/">https://pocketbase.io/</a></li><li>The official website for PocketBase, offering documentation, download links, and news about the project.</li><li><strong>PocketBase GitHub Repository:</strong> <a href="https://github.com/pocketbase/pocketbase">https://github.com/pocketbase/pocketbase</a></li><li>The source code repository on GitHub where developers can contribute and track development progress.</li><li><strong>PocketBase Documentation:</strong> <a href="https://pocketbase.io/docs">https://pocketbase.io/docs</a></li><li>Comprehensive documentation for getting started and advanced usage of PocketBase, including guides for integration and configuration.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a4512b18743" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>