master
master v0.17.83 v0.17.82 v0.17.81 v0.17.80 v0.17.79 v0.17.78 v0.17.77 v0.17.76 v0.17.75 v0.17.74 v0.17.73 v0.17.72 v0.17.71 v0.17.70 v0.17.69 v0.17.68 v0.17.67 v0.17.66 v0.17.65 v0.17.64

embedded_interfaces

Embedding Interfaces
[edit]
You are looking at the docs for the unreleased master branch. The latest version is v0.17.83.

Embedding a GraphQL interface in a Go struct lets you share behavior without duplicating fields. Mark the interface with @goEmbedInterface and gqlgen would generate Base{Interface} struct and embed it to all implementors instead of copying fields.

Core Features

Example

directive @goEmbedInterface on INTERFACE

type Query {
  product(id: ID!): Product!
}

interface Node @goEmbedInterface {
  id: ID!
}

interface Ownable @goEmbedInterface {
  owner: String!
}

type Product implements Node & Ownable {
  id: ID!
  owner: String!
  name: String!
}

Configuration:

# gqlgen.yml
schema:
  - schema.graphqls
model:
  filename: graph/model/models_gen.go

gqlgen generates BaseNode and BaseOwnable structs (only for interfaces with @goEmbedInterface), and Product embeds both:

type BaseNode struct {
	ID string `json:"id"`
}

func (BaseNode) IsNode() {}

type BaseOwnable struct {
	Owner string `json:"owner"`
}

func (BaseOwnable) IsOwnable() {}

type Product struct {
	BaseNode
	BaseOwnable
	Name string `json:"name"`
}

func (Product) IsNode() {}
func (Product) IsOwnable() {}

In resolvers, call methods that return base implementations—no need to construct interface fields manually:

func (r *queryResolver) Product(ctx context.Context, id string) (*model.Product, error) {
	node, err := r.productService.GetNode(ctx, id)
	if err != nil {
		return nil, err
	}

	owner, err := r.productService.GetOwner(ctx, id)
	if err != nil {
		return nil, err
	}

	name, err := r.productService.GetName(ctx, id)
	if err != nil {
		return nil, err
	}

	return &model.Product{
		BaseNode:    node,  // embeds ID from service
		BaseOwnable: owner, // embeds Owner from service
		Name:        name,
	}, nil
}

Limitations