0Pricing
GraphQL APIs with Spring Boot · Урок

Модульная структура схемы с расширениями типов

Сохраняйте большие схемы GraphQL удобными для сопровождения, разделяя их на несколько файлов SDL и расширяя общие корневые типы с помощью ключевого слова extend в Spring Boot.

«Модульная структура схемы с расширениями типов» — бесплатный урок GraphQL APIs with Spring Boot на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения GraphQL APIs with Spring Boot, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс GraphQL APIs with Spring Boot содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

The Monolithic Schema Problem

As an API grows, a single schema.graphqls file becomes thousands of lines, hard to navigate and prone to merge conflicts.

Modularization splits the schema by feature so each team owns a focused slice.

Modularization vs Stitching

This is different from schema stitching. Stitching merges schemas from separate services. Modularization splits one service's schema into many files that load into the same runtime.

Multiple SDL Files in Spring

Spring for GraphQL automatically loads every .graphqls file under src/main/resources/graphql/ and merges them into one schema.

graphql/
  book.graphqls
  author.graphqls
  review.graphqls

The Single Root Problem

GraphQL allows only one Query type. If two files both declare type Query, the schema fails to build with a duplicate-type error.

Extending the Root Type

Declare type Query once, then use extend type Query in other files to add fields. The pieces merge into one root.

# book.graphqls
type Query { books: [Book!]! }

# author.graphqls
extend type Query { authors: [Author!]! }

Extending Object Types

extend works on any object type, not just roots. A reviews module can add a field to Book without editing the book file.

# review.graphqls
extend type Book {
  reviews: [Review!]!
}

Resolvers Stay Modular Too

Each module gets its own controller. The extended field on Book is resolved by a @SchemaMapping in the review module's controller.

@Controller
public class ReviewController {
    @SchemaMapping(typeName = "Book")
    public List<Review> reviews(Book book) {
        return reviewService.forBook(book.getId());
    }
}

Sharing Common Types

Cross-cutting types like PageInfo or shared enums live in a common.graphqls file. Every module references them without redefining.

# common.graphqls
type PageInfo {
  hasNextPage: Boolean!
  endCursor: String
}

Organizing by Feature

Group SDL files and controllers by feature, not by GraphQL kind. Keep book.graphqls next to BookController mentally, so a feature change touches one cohesive area.

Validation at Startup

Spring assembles and validates the merged schema at startup. If an extend references a type that does not exist, the application fails fast with a clear error, catching mistakes early.

Best Practices

Keep modular schemas healthy:

  • Declare each root type once, extend elsewhere
  • One SDL file and controller per feature
  • Centralize shared types in a common file
  • Let startup validation guard your merges

Quick Check

Test your schema modularization knowledge.

Recap

You modularized a large schema:

  • Split SDL into multiple feature files Spring auto-merges
  • Declare root types once, add fields with extend
  • Extend any object type from another module
  • Centralize shared types and keep resolvers modular

Modular schemas scale cleanly across teams and features.

Часто задаваемые вопросы

Урок «Модульная структура схемы с расширениями типов» бесплатный?

Да — полный текст урока «Модульная структура схемы с расширениями типов» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс GraphQL APIs with Spring Boot, подпишись на CoddyKit PRO. Курс GraphQL APIs with Spring Boot содержит 4 уроков всего.

Чему я научусь в уроке «Модульная структура схемы с расширениями типов»?

Сохраняйте большие схемы GraphQL удобными для сопровождения, разделяя их на несколько файлов SDL и расширяя общие корневые типы с помощью ключевого слова extend в Spring Boot. Ты практикуешь GraphQL APIs with Spring Boot с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать GraphQL APIs with Spring Boot?

Предыдущий опыт не требуется. GraphQL APIs with Spring Boot на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Модульная структура схемы с расширениями типов»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке GraphQL APIs with Spring Boot?

Да. Каждый урок GraphQL APIs with Spring Boot включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Создание пользовательских директив
  2. Основы сшивания схем
  3. Объединение нескольких схем GraphQL
  4. Модульная структура схемы с расширениями типов
← Назад к GraphQL APIs with Spring Boot