GraphQL Schema-First, SDL & Shared Models
GraphQL Schema-First, SDL & Shared Models
The previous GraphQL lessons focused on code-first. NestJS also supports schema-first, where the GraphQL schema definition language is the contract and TypeScript types are generated around it. This approach fits teams that treat schema review as the API governance layer.
Core idea
This feature is about controlling how the application is organized and how it behaves at runtime. These are the points a developer should understand before using it in a real project:
- Code-first generates SDL from decorated TypeScript classes; schema-first starts with .graphql files.
- autoSchemaFile is convenient for code-first, while typePaths points Nest to schema-first SDL files.
- DefinitionsFactory can generate TypeScript definitions from the schema.
- Shared models reduce duplication, but GraphQL types should not leak persistence-only fields by default.
- Schema-first encourages explicit API review because schema diffs are easy to inspect.
Practical example
The following example shows the idea in a practical NestJS project. The goal is not to memorize the snippet, but to understand where it belongs in the architecture:
Production checklist
- Pick one GraphQL style per bounded context.
- Review generated SDL in pull requests when using code-first.
- Avoid exposing ORM entities directly as GraphQL contracts.
- Generate TypeScript definitions consistently in schema-first projects.
Summary
This lesson covers an advanced NestJS area that matters when building enterprise applications. Focus on clear boundaries, testable behavior, and choosing the right tool for the context instead of using every feature everywhere.