๐ŸŒ

GraphQL ํ•ต์‹ฌ ์น˜ํŠธ์‹œํŠธ

์Šค์นผ๋ผ ํƒ€์ž…, ์Šคํ‚ค๋งˆ ์ •์˜(SDL), Query/Mutation/Subscription ๋ฌธ๋ฒ•, Spring for GraphQL ์—ฐ๋™(@QueryMapping, @BatchMapping), N+1 DataLoader ์ตœ์ ํ™” ๋ฐ ๋ณด์•ˆ ๋ ˆํผ๋Ÿฐ์Šค

--views
๋‹จ์ˆ˜:
#graphql#api#query#mutation#subscription#sdl#spring#spring-boot#spring-graphql#apollo#dataloader#backend์ตœ์ข… ์—…๋ฐ์ดํŠธ: 2026-09-29

1. GraphQL ํ•ต์‹ฌ ๊ฐœ๋… & REST ๋น„๊ต

๐Ÿ’ป ์‹œ์Šคํ…œ ์„ค์น˜ ๋ฐ ์‹คํ–‰ ์š”๊ตฌ์‚ฌ์–‘ (System Requirements)

ํ•ญ๋ชฉ์ตœ์†Œ ์‚ฌ์–‘ (Minimum)๊ถŒ์žฅ ์‚ฌ์–‘ (Recommended)์ฐธ๊ณ  ๋ฐ ๋น„๊ณ 
์šด์˜์ฒด์ œ (OS)Linux, macOS, Windows 10/11Ubuntu 22.04 LTS, macOS 13+Node.js, Python, Java, Go ๋“ฑ ๋‹ค์–‘ํ•œ ๋Ÿฐํƒ€์ž„ ์ง€์›
CPU1 ์ฝ”์–ด ์ด์ƒ2 ์ฝ”์–ด ~ 4 ์ฝ”์–ด ์ด์ƒ๋ณตํ•ฉ ์ฟผ๋ฆฌ AST ํŒŒ์‹ฑ ๋ฐ ๋ฐ์ดํ„ฐ ๋กœ๋”(DataLoader) ๋ฐฐ์น˜ ์ฒ˜๋ฆฌ
๋ฉ”๋ชจ๋ฆฌ (RAM)1 GB ์ด์ƒ2 GB ~ 4 GB ์ด์ƒ์ธ๋ฉ”๋ชจ๋ฆฌ ์Šคํ‚ค๋งˆ ์ปดํŒŒ์ผ ๋ฐ ์ฟผ๋ฆฌ ์บ์‹œ
๋””์Šคํฌ (Storage)1 GB ์ด์ƒ์˜ ์—ฌ์œ  ๊ณต๊ฐ„5 GB ์ด์ƒ๋Ÿฐํƒ€์ž„ ์˜์กด์„ฑ ํŒจํ‚ค์ง€ (node_modules ๋“ฑ)
๋„คํŠธ์›Œํฌ / ๋Ÿฐํƒ€์ž„Node.js 18+ (Apollo Server), Python 3.10+ (Strawberry) ๋˜๋Š” JDK 17+๊ธฐ๋ณธ HTTP ํฌํŠธ 4000 ๋˜๋Š” 8080GraphQL IDE (Apollo Studio, GraphQL Playground)
[GraphQL vs REST API ํ•ต์‹ฌ ๋น„๊ต]
โ€ข ์—”๋“œํฌ์ธํŠธ     : REST๋Š” ๋ฆฌ์†Œ์Šค๋ณ„ ์ˆ˜๋งŽ์€ ์—”๋“œํฌ์ธํŠธ vs GraphQL์€ ๋‹จ์ผ ์—”๋“œํฌ์ธํŠธ (/graphql)
โ€ข Over-fetching : REST๋Š” ๋ถˆํ•„์š”ํ•œ ํ•„๋“œ๊นŒ์ง€ ์ „๋ถ€ ๋ฐ˜ํ™˜ vs GraphQL์€ ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์š”์ฒญํ•œ ํ•„๋“œ๋งŒ ์ •ํ™•ํžˆ ๋ฐ˜ํ™˜
โ€ข Under-fetching: REST๋Š” ์—ฌ๋Ÿฌ ๋ฒˆ์˜ ์—ฐ์‡„ HTTP ์š”์ฒญ ํ•„์š” vs GraphQL์€ 1๋ฒˆ์˜ ์ฟผ๋ฆฌ๋กœ ์—ฐ๊ด€ ๋ฐ์ดํ„ฐ ์ผ๊ด„ ์กฐํšŒ
โ€ข ํƒ€์ž… ์‹œ์Šคํ…œ   : ์Šคํ‚ค๋งˆ(SDL)๋ฅผ ํ†ตํ•œ ์—„๊ฒฉํ•œ ์ •์  ํƒ€์ž… ๊ฒ€์ฆ ๋ฐ ์ž๋™ ๋ฌธ์„œํ™”(Introspection) ์ง€์›
โ€ข HTTP ๋ฉ”์„œ๋“œ   : ๋Œ€๋ถ€๋ถ„ POST ์š”์ฒญ body(JSON)์— ์ฟผ๋ฆฌ ์ŠคํŠธ๋ง์„ ๋‹ด์•„ ์ „์†ก
# ํด๋ผ์ด์–ธํŠธ ์š”์ฒญ ์˜ˆ์‹œ (POST /graphql)
query {
  user(id: "usr_100") {
    name
    email
    posts(limit: 2) {
      title
    }
  }
}

2. ๊ธฐ๋ณธ ์Šค์นผ๋ผ ํƒ€์ž… & Nullability

# [5๊ฐ€์ง€ ๋‚ด์žฅ ๊ธฐ๋ณธ ์Šค์นผ๋ผ(Scalar) ํƒ€์ž…]
# Int     : ๋ถ€ํ˜ธ ์žˆ๋Š” 32๋น„ํŠธ ์ •์ˆ˜
# Float   : ๋ถ€ํ˜ธ ์žˆ๋Š” ๋ฐฐ์ •๋ฐ€๋„ ๋ถ€๋™์†Œ์ˆ˜์ 
# String  : UTF-8 ๋ฌธ์ž์—ด
# Boolean : true ๋˜๋Š” false
# ID      : ๊ณ ์œ  ์‹๋ณ„์ž (๋‚ด๋ถ€์ ์œผ๋กœ๋Š” String ์ง๋ ฌํ™”)

type Product {
  id: ID!               # ํ•„์ˆ˜(Non-null) ID
  name: String!         # ํ•„์ˆ˜ ๋ฌธ์ž์—ด
  price: Float!         # ํ•„์ˆ˜ ๋ถ€๋™์†Œ์ˆ˜์ 
  rating: Int           # ๋„ ํ—ˆ์šฉ(Nullable) ์ •์ˆ˜ (๊ฐ’ ์—†์œผ๋ฉด null)
  isAvailable: Boolean! # ํ•„์ˆ˜ ๋ถˆ๋ฆฌ์–ธ
  tags: [String!]!      # ๋ฐฐ์—ด๊ณผ ๋‚ด๋ถ€ ์š”์†Œ ๋ชจ๋‘ non-null
}

# [๋ฆฌ์ŠคํŠธ์™€ Nullability ์กฐํ•ฉ ๊ทœ์น™]
# [String]   : ๋ฐฐ์—ด ์ž์ฒด๋„ null ๊ฐ€๋Šฅ, ๋ฐฐ์—ด ๋‚ด๋ถ€ ์š”์†Œ๋„ null ๊ฐ€๋Šฅ (ex: null, [null, "a"])
# [String!]  : ๋ฐฐ์—ด ์ž์ฒด๋Š” null ๊ฐ€๋Šฅ, ๋‚ด๋ถ€ ์š”์†Œ๋Š” ๋ฐ˜๋“œ์‹œ ๋ฌธ์ž์—ด (ex: null, ["a", "b"])
# [String]!  : ๋ฐฐ์—ด์€ ํ•„์ˆ˜ ์กด์žฌ, ๋‚ด๋ถ€ ์š”์†Œ๋Š” null ๊ฐ€๋Šฅ (ex: [], ["a", null])
# [String!]! : ๋ฐฐ์—ด๊ณผ ๋‚ด๋ถ€ ์š”์†Œ ๋ชจ๋‘ ํ•„์ˆ˜ ์กด์žฌ (ex: [], ["a", "b"])

3. ์Šคํ‚ค๋งˆ ์ •์˜ ์–ธ์–ด (SDL: Types, Enums & Custom Scalars)

# ์ปค์Šคํ…€ ์Šค์นผ๋ผ ์„ ์–ธ
scalar DateTime
scalar JSON

# ์—ด๊ฑฐํ˜•(Enum) ์ •์˜
enum UserRole {
  ADMIN
  USER
  GUEST
}

# ๊ฐ์ฒด ํƒ€์ž…(Object Type) ์ •์˜
type User {
  id: ID!
  email: String!
  name: String!
  role: UserRole!
  createdAt: DateTime!
  profile: Profile
  posts: [Post!]!
}

type Profile {
  avatarUrl: String
  bio: String
}

type Post {
  id: ID!
  title: String!
  content: String!
  author: User!
  likeCount: Int!
}

4. Query ์‹ค์ „ ๋ฌธ๋ฒ• (์ธ์ž, ๋ณ„์นญ & ํ”„๋ž˜๊ทธ๋จผํŠธ)

# 1. ์ธ์ž(Arguments) ์ „๋‹ฌ & ์ค‘์ฒฉ ์กฐํšŒ
query GetUserProfile {
  user(id: "usr_42") {
    name
    profile {
      avatarUrl
    }
  }
}

# 2. ๋ณ„์นญ(Aliases) : ๋™์ผํ•œ ํ•„๋“œ๋ฅผ ์„œ๋กœ ๋‹ค๋ฅธ ์ธ์ž๋กœ ํ•œ ๋ฒˆ์— ์กฐํšŒ
query CompareUsers {
  firstUser: user(id: "usr_1") {
    ...UserBasicInfo
  }
  secondUser: user(id: "usr_2") {
    ...UserBasicInfo
  }
}

# 3. ํ”„๋ž˜๊ทธ๋จผํŠธ(Fragments) : ๊ณตํ†ต ํ•„๋“œ ๋ชจ์Œ ์žฌ์‚ฌ์šฉ
fragment UserBasicInfo on User {
  id
  name
  email
  role
}

5. ๋ณ€์ˆ˜(Variables) & ์ง€์‹œ์–ด(@include, @skip)

# ๋ณ€์ˆ˜ ์„ ์–ธ ์‹œ ํƒ€์ž…๊ณผ ๊ธฐ๋ณธ๊ฐ’ ์ง€์ • ($withPosts: Boolean = false)
query GetUserWithCondition($userId: ID!, $withPosts: Boolean!) {
  user(id: $userId) {
    id
    name
    email
    # @include : ์กฐ๊ฑด์ด true์ผ ๋•Œ๋งŒ ํ•„๋“œ ํฌํ•จ
    posts @include(if: $withPosts) {
      id
      title
    }
    # @skip : ์กฐ๊ฑด์ด true์ด๋ฉด ํ•„๋“œ ์ œ์™ธ
    profile @skip(if: $withPosts) {
      bio
    }
  }
}

# [GraphQL ๋ณ€์ˆ˜ JSON (HTTP Body์˜ "variables" ํ•„๋“œ)]
# {
#   "userId": "usr_42",
#   "withPosts": true
# }

6. Mutation ๋ฐ์ดํ„ฐ ๋ณ€๊ฒฝ & ์ž…๋ ฅ ๊ฐ์ฒด(Input)

# ์Šคํ‚ค๋งˆ ์ •์˜: Mutation ์ „์šฉ Input Object
input CreatePostInput {
  title: String!
  content: String!
  tags: [String!]
}

# ๋ณ€๊ฒฝ ๊ฒฐ๊ณผ Payload ๋ฐ˜ํ™˜ ํŒจํ„ด (UI ์บ์‹œ ๊ฐฑ์‹  ์šฉ์ด)
type CreatePostPayload {
  success: Boolean!
  post: Post
  clientMutationId: String
}

# Mutation ์š”์ฒญ ์ฟผ๋ฆฌ
mutation CreateNewPost($input: CreatePostInput!) {
  createPost(input: $input) {
    success
    post {
      id
      title
      createdAt
      author {
        id
        name
      }
    }
  }
}

7. Subscription ์‹ค์‹œ๊ฐ„ ์ด๋ฒคํŠธ ๊ตฌ๋… (WebSockets)

# ์Šคํ‚ค๋งˆ ์ •์˜
type Subscription {
  postCreated: Post!
  commentAdded(postId: ID!): Comment!
  messageSent(roomId: ID!): Message!
}

# ํด๋ผ์ด์–ธํŠธ ๊ตฌ๋… ์š”์ฒญ (WebSocket ํ”„๋กœํ† ์ฝœ ws:// ๋˜๋Š” wss://)
subscription WatchRoomMessages($roomId: ID!) {
  messageSent(roomId: $roomId) {
    id
    sender {
      name
    }
    text
    sentAt
  }
}
[์‹ค๋ฌด ๊ถŒ์žฅ์‚ฌํ•ญ]
โ€ข ํ”„๋กœํ† ์ฝœ : graphql-ws ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์‚ฌ์šฉ ๊ถŒ์žฅ (๊ตฌํ˜• subscriptions-transport-ws๋Š” deprecated)
โ€ข ํ•˜ํŠธ๋น„ํŠธ : ์ฃผ๊ธฐ์ ์ธ Ping/Pong ํŒจํ‚ท์œผ๋กœ ๋ชจ๋ฐ”์ผ ๋Š๊น€ ๋ฐ ์œ ํœด ์ปค๋„ฅ์…˜ ๊ฐ์ง€

8. ์ธํ„ฐํŽ˜์ด์Šค(Interface) & ์œ ๋‹ˆ์˜จ(Union) ๋‹คํ˜•์„ฑ

# ์ธํ„ฐํŽ˜์ด์Šค ์ •์˜
interface Node {
  id: ID!
}

interface Content {
  id: ID!
  title: String!
  author: User!
}

# ์ธํ„ฐํŽ˜์ด์Šค ๊ตฌํ˜„
type Article implements Content {
  id: ID!
  title: String!
  author: User!
  wordCount: Int!
}

type Video implements Content {
  id: ID!
  title: String!
  author: User!
  durationSeconds: Int!
}

# ์œ ๋‹ˆ์˜จ(Union) ํƒ€์ž… ์ •์˜ (์Šค์นผ๋ผ๊ฐ€ ์•„๋‹Œ Object ํƒ€์ž…๋“ค์˜ ํ•ฉ์ง‘ํ•ฉ)
union SearchResult = Article | Video | User

# ์ธ๋ผ์ธ ํ”„๋ž˜๊ทธ๋จผํŠธ(... on Type) ๋ฐ __typename์„ ํ™œ์šฉํ•œ ์ฟผ๋ฆฌ
query UniversalSearch($keyword: String!) {
  search(keyword: $keyword) {
    __typename # ์‹ค์ œ ๊ฐ์ฒด ํƒ€์ž…๋ช… ๋ฐ˜ํ™˜ ("Article", "Video", "User")
    ... on Article {
      id
      title
      wordCount
    }
    ... on Video {
      id
      title
      durationSeconds
    }
    ... on User {
      id
      name
      email
    }
  }
}

9. ๋ฐฑ์—”๋“œ ๋ฆฌ์กธ๋ฒ„ & N+1 ํ•ด๊ฒฐ (DataLoader)

// ๋ฆฌ์กธ๋ฒ„ ๊ธฐ๋ณธ ์‹œ๊ทธ๋‹ˆ์ฒ˜: (parent, args, context, info)
const resolvers = {
  Query: {
    user: async (_, { id }, { db }) => db.findUserById(id),
    posts: async (_, { limit }, { db }) => db.findRecentPosts(limit),
  },
  Post: {
    // [N+1 ๋ฐœ์ƒ ์›์ธ]: Post๊ฐ€ 100๊ฑด์ด๋ฉด author ๋ฆฌ์กธ๋ฒ„๊ฐ€ 100๋ฒˆ ๊ฐœ๋ณ„ SQL ์‹คํ–‰!
    // author: async (post, _, { db }) => db.findUserById(post.authorId),

    // [DataLoader ํ•ด๊ฒฐ]: 1๊ฐœ์˜ ์ด๋ฒคํŠธ ๋ฃจํ”„ ํ‹ฑ ๋™์•ˆ์˜ ์š”์ฒญ์„ ๋ชจ์•„ 1๋ฒˆ์˜ 'WHERE id IN (...)'์œผ๋กœ ์ผ๊ด„ ์กฐํšŒ
    author: (post, _, { loaders }) => loaders.userLoader.load(post.authorId),
  },
};

// DataLoader ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ (์š”์ฒญ(Context) ๋‹จ์œ„ ๊ฒฉ๋ฆฌ ํ•„์ˆ˜!)
import DataLoader from 'dataloader';

export function createLoaders(db) {
  return {
    userLoader: new DataLoader(async (userIds) => {
      // SELECT * FROM users WHERE id IN (1, 2, 3...)
      const users = await db.findUsersByIds(userIds);
      // ๋ฐ˜๋“œ์‹œ ์ „๋‹ฌ๋ฐ›์€ userIds ์ˆœ์„œ์™€ 1:1๋กœ ๋งคํ•‘ํ•˜์—ฌ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•จ!
      const userMap = new Map(users.map(u => [u.id, u]));
      return userIds.map(id => userMap.get(id) || null);
    }),
  };
}

10. ํŽ˜์ด์ง€๋„ค์ด์…˜ (Cursor-based Relay Connection)

# ํ‘œ์ค€ Relay Connection ๋ช…์„ธ
type PostConnection {
  edges: [PostEdge!]!
  pageInfo: PageInfo!
  totalCount: Int!
}

type PostEdge {
  cursor: String!
  node: Post!
}

type PageInfo {
  hasNextPage: Boolean!
  hasPreviousPage: Boolean!
  startCursor: String
  endCursor: String
}

# ์ฟผ๋ฆฌ ์š”์ฒญ: ํŠน์ • ์ปค์„œ ์ดํ›„(after) N๊ฐœ(first) ์กฐํšŒ
query GetPaginatedPosts($first: Int!, $after: String) {
  posts(first: $first, after: $after) {
    totalCount
    pageInfo {
      hasNextPage
      endCursor
    }
    edges {
      cursor
      node {
        id
        title
        likeCount
      }
    }
  }
}

11. ์—๋Ÿฌ ์‘๋‹ต ๊ตฌ์กฐ & ํ•ธ๋“ค๋ง ๋ชจ๋ฒ” ์‚ฌ๋ก€

{
  "data": {
    "user": null
  },
  "errors": [
    {
      "message": "ํ•ด๋‹น ์‚ฌ์šฉ์ž๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.",
      "locations": [{ "line": 2, "column": 3 }],
      "path": ["user"],
      "extensions": {
        "code": "NOT_FOUND",
        "invalidArgs": ["usr_999"],
        "timestamp": "2026-09-29T11:30:00Z"
      }
    }
  ]
}
[GraphQL ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ•ต์‹ฌ ์›์น™]
โ€ข HTTP 200 OK  : GraphQL ์—”์ง„์ด ์ฟผ๋ฆฌ๋ฅผ ์ •์ƒ ํŒŒ์‹ฑ/์‹คํ–‰ํ–ˆ๋‹ค๋ฉด ํ•„๋“œ ์—๋Ÿฌ๊ฐ€ ์žˆ๋”๋ผ๋„ HTTP ์ƒํƒœ ์ฝ”๋“œ๋Š” 200 ๋ฐ˜ํ™˜
โ€ข ๋ถ€๋ถ„ ์‘๋‹ต     : ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š์€ ๋‹ค๋ฅธ ํ•„๋“œ๋Š” "data"์— ์ •์ƒ ํฌํ•จ๋˜์–ด ๋ Œ๋”๋ง ๊ฐ€๋Šฅ (Partial Data)
โ€ข extensions   : ํด๋ผ์ด์–ธํŠธ ๋ถ„๊ธฐ ์ฒ˜๋ฆฌ๋ฅผ ์œ„ํ•ด ํ‘œ์ค€ ์ฝ”๋“œ(UNAUTHENTICATED, FORBIDDEN, BAD_USER_INPUT)๋ฅผ extensions์— ํฌํ•จ
โ€ข ๋ณด์•ˆ ์ฃผ์˜    : ์šด์˜(Production) ํ™˜๊ฒฝ์—์„œ๋Š” ๋‚ด๋ถ€ SQL/์ŠคํƒํŠธ๋ ˆ์ด์Šค๊ฐ€ ํด๋ผ์ด์–ธํŠธ๋กœ ๋…ธ์ถœ๋˜์ง€ ์•Š๋„๋ก ์—๋Ÿฌ ๋งˆ์Šคํ‚น ํ•„์ˆ˜

12. ์šด์˜ ๋ฐ ๋ณด์•ˆ ๋ชจ๋ฒ” ์‚ฌ๋ก€ (Security & Production)

[GraphQL ๋ณด์•ˆ 5๋Œ€ ์ˆ˜์น™]
1. ์ธํŠธ๋กœ์ŠคํŽ™์…˜(Introspection) ๋น„ํ™œ์„ฑํ™”
   - ์šด์˜ ๋ฐฐํฌ ์‹œ __schema, __type ์ฟผ๋ฆฌ๋ฅผ ๋ง‰์•„ ๋‚ด๋ถ€ ๊ตฌ์กฐ ๋…ธ์ถœ ๋ฐฉ์ง€
2. ์ฟผ๋ฆฌ ๊นŠ์ด ์ œํ•œ (Query Depth Limit)
   - ์•…์˜์ ์ธ ๋ฌดํ•œ ์ˆœํ™˜ ์ฟผ๋ฆฌ ๋ฐฉ์ง€ (user { posts { author { posts { author... } } } })
3. ์ฟผ๋ฆฌ ๋ณต์žก๋„ ๋ถ„์„ (Query Cost/Complexity Analysis)
   - ๊ณ„์‚ฐ ๋น„์šฉ์ด ํฐ ํ•„๋“œ์— ๊ฐ€์ค‘์น˜๋ฅผ ๋ถ€์—ฌํ•˜๊ณ , ์ž„๊ณ„์น˜ ์ดˆ๊ณผ ์ฟผ๋ฆฌ ๊ฑฐ๋ถ€
4. ์ง€์† ์ฟผ๋ฆฌ (Persisted Queries)
   - ํด๋ผ์ด์–ธํŠธ๋Š” ์ฟผ๋ฆฌ ๋ณธ๋ฌธ ๋Œ€์‹  ์‚ฌ์ „์— ๋“ฑ๋ก๋œ ํ•ด์‹œ(SHA-256)๊ฐ’๋งŒ ์ „์†กํ•˜์—ฌ ๋Œ€์—ญํญ ์ ˆ์•ฝ ๋ฐ ์ž„์˜ ์ฟผ๋ฆฌ ์ฐจ๋‹จ
5. ๋ฐฐ์น˜ ์š”์ฒญ ๊ฐœ์ˆ˜ ์ œํ•œ (Batching Attack ๋ฐฉ์ง€)
   - ๋‹จ์ผ HTTP ์š”์ฒญ์— ์ˆ˜์ฒœ ๊ฐœ์˜ query ๋ฐฐ์—ด์„ ๋‹ด์•„ ๋ณด๋‚ด๋Š” ๋ฌด์ฐจ๋ณ„ ๋Œ€์ž…(Brute-force) ๊ณต๊ฒฉ ์ฐจ๋‹จ

13. Spring for GraphQL ์„ค์ • & ์Šคํ‚ค๋งˆ ๊ตฌ์„ฑ

// build.gradle (Spring Boot 3.x / 2.7+ ๊ณต์‹ ์Šคํƒ€ํ„ฐ)
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-graphql'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    // WebSocket ๊ตฌ๋… ์ง€์› ํ•„์š” ์‹œ ์ถ”๊ฐ€
    implementation 'org.springframework.boot:spring-boot-starter-websocket'
}
# application.yml
spring:
  graphql:
    graphiql:
      enabled: true            # ๋ธŒ๋ผ์šฐ์ € ํ…Œ์ŠคํŠธ UI ํ™œ์„ฑํ™” (http://localhost:8080/graphiql)
      path: /graphiql
    http:
      path: /graphql           # GraphQL ๋‹จ์ผ HTTP ์—”๋“œํฌ์ธํŠธ (๊ธฐ๋ณธ๊ฐ’: /graphql)
    websocket:
      path: /graphql           # Subscription์šฉ ์›น์†Œ์ผ“ ์—”๋“œํฌ์ธํŠธ
    schema:
      printer:
        enabled: true          # ์„œ๋ฒ„ ๊ธฐ๋™ ์‹œ ๋ณ‘ํ•ฉ๋œ ์ตœ์ข… ์Šคํ‚ค๋งˆ๋ฅผ ์ฝ˜์†”์— ์ถœ๋ ฅ
# src/main/resources/graphql/schema.graphqls
# Spring Boot๊ฐ€ ํ•ด๋‹น ๋””๋ ‰ํ„ฐ๋ฆฌ์˜ ๋ชจ๋“  .graphqls ํŒŒ์ผ์„ ์ž๋™ ๋กœ๋“œํ•˜์—ฌ ๋ณ‘ํ•ฉํ•ฉ๋‹ˆ๋‹ค.
type Query {
    bookById(id: ID!): Book
    allBooks: [Book!]!
}

type Mutation {
    createBook(input: CreateBookInput!): Book!
}

type Subscription {
    bookAdded: Book!
}

type Book {
    id: ID!
    title: String!
    pageCount: Int!
    author: Author!
}

type Author {
    id: ID!
    name: String!
}

input CreateBookInput {
    title: String!
    pageCount: Int!
    authorId: ID!
}

14. Spring ์ปจํŠธ๋กค๋Ÿฌ ๊ตฌํ˜„ (@QueryMapping, @MutationMapping)

package com.example.demo.controller;

import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.MutationMapping;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.graphql.data.method.annotation.SubscriptionMapping;
import org.springframework.stereotype.Controller;
import reactor.core.publisher.Flux;

import java.util.List;

@Controller
public class BookController {

    private final BookService bookService;

    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    // 1. Query.bookById(id: ID!) ๋งคํ•‘ (๋ฉ”์„œ๋“œ๋ช…๊ณผ ์Šคํ‚ค๋งˆ ํ•„๋“œ๋ช… ์ผ์น˜)
    @QueryMapping
    public Book bookById(@Argument Long id) {
        return bookService.findById(id);
    }

    // 2. Query.allBooks ๋งคํ•‘
    @QueryMapping
    public List<Book> allBooks() {
        return bookService.findAll();
    }

    // 3. Mutation.createBook(input: CreateBookInput!) ๋งคํ•‘
    // Java 17+ record ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ณ„๋„ ๋งคํผ ์—†์ด ์ž๋™ ๋ฐ”์ธ๋”ฉ
    @MutationMapping
    public Book createBook(@Argument CreateBookInput input) {
        return bookService.create(input);
    }

    // 4. Subscription.bookAdded ๋งคํ•‘ (Reactive Flux ๋ฐ˜ํ™˜)
    @SubscriptionMapping
    public Flux<Book> bookAdded() {
        return bookService.getBookAddedFlux();
    }
}

// DTO๋Š” record๋กœ ์ •์˜ ๊ถŒ์žฅ
public record CreateBookInput(String title, int pageCount, Long authorId) {}

15. Spring N+1 ํ•ด๊ฒฐ (@BatchMapping & DataLoader)

@Controller
public class BookAuthorController {

    private final AuthorService authorService;

    public BookAuthorController(AuthorService authorService) {
        this.authorService = authorService;
    }

    // [๋‹จ๊ฑด ํ•ด๊ฒฐ]: @SchemaMapping (N+1 ๋ฌธ์ œ ๋ฐœ์ƒ ๊ฐ€๋Šฅ!)
    // allBooks๋กœ ์ฑ… 100๊ฑด ์กฐํšŒ ์‹œ, ๊ฐ ์ฑ…๋งˆ๋‹ค author ๋ฉ”์„œ๋“œ๊ฐ€ 100๋ฒˆ ํ˜ธ์ถœ๋จ
    // @SchemaMapping(typeName = "Book", field = "author")
    // public Author getAuthor(Book book) {
    //     return authorService.findById(book.authorId());
    // }

    // [โญ๏ธ ์‹ค๋ฌด ๊ถŒ์žฅ]: @BatchMapping (DataLoader ์ž๋™ ๊ตฌ์„ฑ)
    // ๋ถ€๋ชจ ๋ฆฌ์ŠคํŠธ(List<Book>)๋ฅผ ํ•œ ๋ฒˆ์— ์ธ์ž๋กœ ์ „๋‹ฌ๋ฐ›์•„ ์™ธ๋ž˜ํ‚ค ๋ชฉ๋ก์„ ์ถ”์ถœํ•˜๊ณ ,
    // "SELECT * FROM author WHERE id IN (...)" 1๋ฒˆ์˜ ์ฟผ๋ฆฌ๋กœ ๋ฌถ์–ด์„œ Map ํ˜•ํƒœ๋กœ ๋ฐ˜ํ™˜
    @BatchMapping(typeName = "Book", field = "author")
    public Map<Book, Author> author(List<Book> books) {
        List<Long> authorIds = books.stream().map(Book::authorId).toList();
        Map<Long, Author> authorMap = authorService.findAllByIds(authorIds);

        // Book ๊ฐ์ฒด์™€ ๋Œ€์‘ํ•˜๋Š” Author ๊ฐ์ฒด๋ฅผ Map์œผ๋กœ ๋งคํ•‘ํ•˜์—ฌ ๋ฐ˜ํ™˜
        return books.stream()
            .collect(Collectors.toMap(
                book -> book,
                book -> authorMap.get(book.authorId())
            ));
    }
}
[@BatchMapping ํ•ต์‹ฌ ๋™์ž‘ ๋ฐฉ์‹]
โ€ข GraphQL Java์˜ DataLoader๋ฅผ ์ˆ˜๋™ ๋“ฑ๋กํ•  ํ•„์š” ์—†์ด Spring์ด ๋Ÿฐํƒ€์ž„์— ์ž๋™ ์ฃผ์ž…
โ€ข ๋™์ผ ์‹คํ–‰ ์ปจํ…์ŠคํŠธ(Event Loop/Execution loop) ๋‚ด์˜ Book ํ•„๋“œ ์š”์ฒญ์„ ํ•œ๊ณณ์— ์ทจํ•ฉํ•˜์—ฌ 1ํšŒ ๋ฐฐ์น˜ ์กฐํšŒ ์‹คํ–‰
โ€ข ๋ฐ˜ํ™˜ ํƒ€์ž…: Map<๋ถ€๋ชจ, ์ž์‹> ๋˜๋Š” Flux<์ž์‹> (์ˆœ์„œ ๋ณด์žฅํ˜•) ์ง€์›

16. Spring ์˜ˆ์™ธ ์ฒ˜๋ฆฌ & ๋ณด์•ˆ (@GraphQlExceptionHandler & Security)

// 1. ์ „์—ญ GraphQL ์˜ˆ์™ธ ํ•ธ๋“ค๋Ÿฌ (@ControllerAdvice)
@ControllerAdvice
public class GraphQlExceptionResolver {

    @GraphQlExceptionHandler
    public GraphQLError handleNotFound(EntityNotFoundException ex, DataFetchingEnvironment env) {
        return GraphQLError.newError()
            .errorType(ErrorType.NOT_FOUND)
            .message(ex.getMessage())
            .path(env.getExecutionStepInfo().getPath())
            .location(env.getField().getSourceLocation())
            .extensions(Map.of(
                "errorCode", "RESOURCE_NOT_FOUND",
                "timestamp", Instant.now().toString()
            ))
            .build();
    }
}
// 2. Spring Security ์—ฐ๋™ (๋ฉ”์„œ๋“œ ๋ณด์•ˆ ์ ์šฉ)
@Controller
public class SecureAdminController {

    // Spring Security์˜ @PreAuthorize๋ฅผ ์ปจํŠธ๋กค๋Ÿฌ ๋ฉ”์„œ๋“œ์— ๊ทธ๋Œ€๋กœ ์ ์šฉ ๊ฐ€๋Šฅ!
    @PreAuthorize("hasRole('ADMIN')")
    @MutationMapping
    public Boolean deleteBook(@Argument Long id) {
        bookService.delete(id);
        return true;
    }

    // ํ˜„์žฌ ์ธ์ฆ๋œ ์‚ฌ์šฉ์ž Principal ์ฃผ์ž…
    @QueryMapping
    public UserProfile me(@AuthenticationPrincipal CustomUserDetails user) {
        return user.toProfile();
    }
}
๐Ÿ’ฌ

์˜๊ฒฌ ๋ฐ ์งˆ๋ฌธ

0
0 / 1500