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!
}
| Benefit | Detail |
|---|---|
| Identity-scoped queries | Implicit "current user" |
| Cache key stability | Single root per session |
| Authorization clarity | Permissions 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
| Technique | Detail |
|---|---|
| Interface implementation | Share fields across types |
| Fragment composition | Reuse selection sets |
| Schema modules | Combine 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
| Layer | Responsibility |
|---|---|
| Resolver | Argument validation, auth, call service |
| Service | Business logic, orchestration, transactions |
| Repository | Persistence access |
9. Implementing Facade Pattern
| Use | Detail |
|---|---|
| Single API over many sources | GraphQL itself is a façade |
| Hide legacy | Map old REST/SOAP into clean schema |
| Aggregate responses | Combine multiple back-end calls into one type |