Implementing Design Patterns

1. Using Relay Connection Pattern

Example: Connection types

type UserConnection {
  edges: [UserEdge!]!
  pageInfo: PageInfo!
  totalCount: Int
}
type UserEdge { cursor: String!, node: User! }
type PageInfo {
  hasNextPage: Boolean!
  hasPreviousPage: Boolean!
  startCursor: String
  endCursor: String
}

2. Using Node Interface Pattern

Example: Global ID

interface Node { id: ID! }
type User implements Node {
  id: ID!  # base64("User:123")
  email: EmailAddress!
}
type Query {
  node(id: ID!): Node
  nodes(ids: [ID!]!): [Node]!
}

3. Implementing Viewer Pattern

Example: Viewer root

type Query {
  viewer: Viewer!
}
type Viewer {
  user: User!
  notifications(first: Int): NotificationConnection!
  preferences: Preferences!
}
BenefitDetail
Identity-scoped queriesImplicit "current user"
Cache key stabilitySingle root per session
Authorization clarityPermissions tied to viewer

4. Using Payload Types Pattern

Example: Mutation payload

type CreateUserPayload {
  user: User
  userEdge: UserEdge  # for cache insertion
  clientMutationId: String
  errors: [UserError!]
}

5. Implementing Result Types Pattern

Example: Union result

union LoginResult = LoginSuccess | InvalidCredentials | MFARequired

type LoginSuccess { token: String!, user: User! }
type InvalidCredentials { message: String! }
type MFARequired { challengeId: ID! }

6. Using Composition Pattern

TechniqueDetail
Interface implementationShare fields across types
Fragment compositionReuse selection sets
Schema modulesCombine modular type defs

7. Implementing Repository Pattern

Example: Repository

class UserRepository {
  constructor(private db, private cache) {}
  findById(id) { return this.cache.wrap(`u:${id}`, () => this.db.user.findUnique({ where: { id } })); }
  create(input) { return this.db.user.create({ data: input }); }
}

context: () => ({ users: new UserRepository(db, cache) })

8. Using Service Layer Pattern

LayerResponsibility
ResolverArgument validation, auth, call service
ServiceBusiness logic, orchestration, transactions
RepositoryPersistence access

9. Implementing Facade Pattern

UseDetail
Single API over many sourcesGraphQL itself is a façade
Hide legacyMap old REST/SOAP into clean schema
Aggregate responsesCombine multiple back-end calls into one type

10. Using Factory Pattern

Example: Loader factory

const createLoaders = (db) => ({
  userById: new DataLoader((ids) => batchUsers(db, ids)),
  postsByUser: new DataLoader((ids) => batchPostsByUser(db, ids))
});

context: () => ({ db, loaders: createLoaders(db) })