[๐Ÿš€Apollo] Cache - Overview

5186 ๋‹จ์–ด apollooverviewCacheCache

Apollo ๊ณต์‹ ๋ฌธ์„œ๋ฅผ ๊ทธ๋Œ€๋กœ ๋ฒˆ์—ญํ•œ ๊ธ€ ์ž…๋‹ˆ๋‹ค.

Caching in Apollo Client

  • apollo client store๋Š” graphQL์˜ ๊ฒฐ๊ณผ๋ฅผ ์ €์žฅํ•ด ๋‘๊ธฐ ๋•Œ๋ฌธ์— ์ด๋ฏธ ์ €์žฅ๋œ ๋ฐ์ดํ„ฐ๋ฅผ ๋‹ค์‹œ ์š”์ฒญํ•  ๋•Œ์—๋Š” ์ฆ‰์‹œ ๊ทธ ๊ฒฐ๊ณผ ๊ฐ’์„ ์‘๋‹ตํ•ฉ๋‹ˆ๋‹ค.

How is data stored

  • ์•„ํด๋กœ ํด๋ผ์ด์–ธํŠธ๋Š” InMemoryCache์˜ Flat Lookup Table๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.
  • ๊ทธ๋Ÿฐ๋ฐ GraphQL์ด ์‘๋‹ตํ•˜๋Š” ๋Œ€๋ถ€๋ถ„์˜ ๋ฐ์ดํ„ฐ๋Š” Flat ํ•˜์ง€ ์•Š์€ Object ํ˜•ํƒœ์ธ๋ฐ ์ด๋ฅผ ์–ด๋–ป๊ฒŒ Flatํ•˜๊ฒŒ ์ €์žฅํ• ๊นŒ์š”?
  • nomalize๋ฅผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.
{
  "data": {
    "person": {
      "__typename": "Person",
      "id": "cGVvcGxlOjE=",
      "name": "Luke Skywalker",
      "homeworld": {
        "__typename": "Planet",
        "id": "cGxhbmV0czox",
        "name": "Tatooine"
      }
    }
  }
}

Data normalization

  1. Identify objects
  • ์šฐ์„  ๊ตฌ๋ณ„๊ฐ€๋Šฅํ•œ object๋“ค์„ ์ „๋ถ€ ํŒŒ์•…ํ•ฉ๋‹ˆ๋‹ค.
  • ์œ„์˜ ์˜ˆ์—์„œ๋Š” person๊ณผ homeworld๊ฐ€ ๊ทธ๊ฒƒ.
  1. Generate cache IDs
  • ๊ฐ๊ฐ์˜ object์— ID ๋ถ€์—ฌํ•˜๊ธฐ
  • ๊ธฐ๋ณธ์ ์œผ๋กœ __typename๊ณผ id์˜ ์กฐํ•ฉ์œผ๋กœ ์ด๋ฅผ ๋งŒ๋“ ๋‹ค.
  • Person:cGVvcGxlOjE=, Planet:cGxhbmV0czox ์ด๋Ÿฐ ์‹์œผ๋กœ
  1. Object๋Š” reference๋กœ ์น˜ํ™˜ํ•˜๊ธฐ
  • ์•„๋ž˜ ์˜ˆ์‹œ๋ฅผ ๋ณด๋ฉด homeworld๊ฐ€ ์น˜ํ™˜๋œ ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.
  • ๋งŒ์•ฝ ๋‹ค๋ฅธ ์ฟผ๋ฆฌ์—์„œ ๋˜‘๊ฐ™์€ homeworld๋ฅผ ์ €์žฅํ•ด์•ผ ํ•œ๋‹ค๋ฉด, ๊ฐ™์€ ref๋ฅผ ๋ณด๊ธฐ ๋•Œ๋ฌธ์— ๋ฐ์ดํ„ฐ ์ ˆ์•ฝ!
{
  "__typename": "Person",
  "id": "cGVvcGxlOjE=",
  "name": "Luke Skywalker",
  "homeworld": {
    "__typename": "Planet",
    "id": "cGxhbmV0czox",
    "name": "Tatooine"
  }
}
{
  "__typename": "Person",
  "id": "cGVvcGxlOjE=",
  "name": "Luke Skywalker",
  "homeworld": {
    "__ref": "Planet:cGxhbmV0czox"
  }
}
  1. Store normalized objects
  • ๋งŒ์•ฝ ๊ฐ™์€ ID์˜ ์บ์‹œ๊ฐ€ ๋“ค์–ด์˜จ๋‹ค๋ฉด, ์ด๋Š” ๊ธฐ์กด ์บ์‹œ์— merge ๋œ๋‹ค.

Visualizing the cache

  • Apollo Client Devtools๋ฅผ ๊น”์•„๋ผ!

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ