Skip to content

Conversation

@productdevbook
Copy link
Owner

@productdevbook productdevbook commented Sep 1, 2025

🚀 Feature Implementation: Apollo Federation Subgraph Support

📋 Overview

This PR implements comprehensive Apollo Federation support for nitro-graphql, enabling distributed GraphQL architectures with both GraphQL Yoga and Apollo Server frameworks.

🔧 Technical Implementation

1. Federation Configuration Types

Added FederationConfig interface to support federation settings:

// src/types/index.ts
export interface FederationConfig {
  enabled: boolean
  serviceName?: string
  serviceVersion?: string
  serviceUrl?: string
}

2. Virtual Module Configuration System

Replaced process.env dependencies with typed virtual module:

// #nitro-internal-virtual/module-config
import { moduleConfig } from '#nitro-internal-virtual/module-config'
const federationEnabled = moduleConfig.federation?.enabled

3. Dynamic Dependency Loading

Implemented optional @apollo/subgraph integration:

// src/routes/apollo-server.ts & graphql-yoga.ts
async function loadFederationSupport() {
  try {
    const apolloSubgraph = await import('@apollo/subgraph')
    buildSubgraphSchema = apolloSubgraph.buildSubgraphSchema
  } catch {
    buildSubgraphSchema = false // Graceful fallback
  }
}

4. Schema Builder Integration

  • Uses buildSubgraphSchema when federation is enabled
  • Converts string typeDefs to DocumentNode using parse()
  • Falls back to makeExecutableSchema when federation unavailable

5. GraphQL Codegen Integration

Enhanced type generation with federation support:

// src/utils/server-codegen.ts
const defaultConfig = {
  // ... existing config
  ...(config.federation?.enabled && { federation: true }),
}

6. Auto-Import Functions

Added federation helper functions:

  • defineReference() - For __resolveReference resolvers
  • defineEntity() - For federated entity types
  • defineSubgraph() - For subgraph configuration

🎯 Framework Support

GraphQL Yoga Implementation

  • Integrated buildSubgraphSchema in schema creation
  • Maintains Apollo Sandbox for federation queries
  • Async schema building with proper error handling

Apollo Server Implementation

  • Fixed async initialization with defineEventHandler
  • Promise-based server creation to handle async schema
  • Proper H3 handler integration

🧪 Testing Infrastructure

Federation Playground

Created /playground-federation/ with:

  • Federation schema with @key directive
  • Entity resolver with __resolveReference
  • Multiple Nitro configs for testing both frameworks
  • GraphQL config for proper tooling support

Test Schema Example

extend schema
  @link(url: "https://specs.apollo.dev/federation/v2.5", import: ["@key"])

type User @key(fields: "id") {
  id: ID!
  email: String!
  name: String!
}

📦 Dependency Management

  • Added @apollo/subgraph as optional peerDependency
  • Updated pnpm workspace to include federation playground
  • Catalog management for consistent versions

🔍 Virtual Module System

Enhanced virtual module architecture:

// src/virtual.d.ts
declare module '#nitro-internal-virtual/module-config' {
  import type { NitroGraphQLOptions } from '../types'
  export const moduleConfig: Partial<NitroGraphQLOptions>
}

🔍 AST Parsing Enhancement

Extended resolver scanning to detect federation functions:

// src/utils/index.ts
if (decl.init.callee.name === 'defineReference') {
  exports.imports.push({
    name: decl.id.name,
    type: 'resolver',
    // ...
  })
}

⚡ Performance Considerations

  • Lazy loading of federation dependencies
  • Singleton pattern for server instances
  • Efficient schema caching
  • Minimal overhead when federation disabled
  • Build-time config resolution (no runtime env vars)

🔒 Backward Compatibility

  • Zero breaking changes for existing projects
  • Optional dependency approach
  • Graceful degradation when packages missing
  • Configuration-based activation (no environment variables needed)

🧩 Integration Points

Type Generation

  • Federation directives added to schema when enabled
  • Proper TypeScript types for federated resolvers
  • Client-side type generation unaffected

Development Experience

  • Hot reload support in dev mode
  • Clear error messages and warnings
  • Consistent with existing nitro-graphql patterns
  • Type-safe configuration through virtual modules

📊 Code Changes Summary

  • 27 files changed: 633 insertions, 42 deletions
  • New playground: Complete federation testing environment
  • Enhanced utilities: Federation-aware code generation
  • Route handlers: Both frameworks support federation
  • Type definitions: Full TypeScript support
  • Virtual modules: Centralized config system

✅ Verification Checklist

  • Federation queries (_service, _entities) functional
  • Entity resolution with __resolveReference working
  • GraphQL Yoga federation support tested
  • Apollo Server federation support tested
  • TypeScript compilation successful
  • ESLint passing
  • Graceful fallback when dependencies missing
  • Existing projects unaffected
  • Hot reload working in dev mode
  • Auto-imports functioning correctly
  • No environment variable dependencies
  • Build-time configuration resolution

🔗 Related Issues

Closes #33


This implementation provides a robust foundation for Apollo Federation in nitro-graphql while maintaining the library's core principles of simplicity, type safety, and developer experience. The new virtual module system eliminates runtime environment dependencies in favor of build-time configuration.

- Add optional @apollo/subgraph integration with dynamic imports
- Support both GraphQL Yoga and Apollo Server frameworks
- Add federation helper functions (defineReference, defineEntity, defineSubgraph)
- Enable federation: true in GraphQL Codegen when federation is active
- Add federation playground for testing
- Maintain backward compatibility with existing projects

Closes #33
- Replace process.env.NITRO_GRAPHQL_FEDERATION with typed virtual module
- Add #nitro-internal-virtual/module-config for centralized config access
- Remove environment variable dependencies in favor of build-time config
- Enable access to all NitroGraphQLOptions through moduleConfig
- Maintain type safety with proper TypeScript declarations

This provides better developer experience and eliminates runtime env dependencies.
Resolved merge conflicts by combining:
- Apollo Federation support (from federation branch)
- Nuxt layer support and codebase cleanup (from main branch)

This integrates both feature sets while maintaining compatibility.
@productdevbook productdevbook merged commit ba6c676 into main Sep 5, 2025
1 check passed
@productdevbook productdevbook deleted the feat/federation-codegen-support branch September 5, 2025 06:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature Request: Apollo Federation Support

2 participants