Upgrade to Pro — share decks privately, control downloads, hide ads and more …

隣の API のデータを Rails らしく、しなやかに扱う / Handling next-...

osyoyu
October 22, 2022

隣の API のデータを Rails らしく、しなやかに扱う / Handling next-door API data in Rails

osyoyu

October 22, 2022
Tweet

More Decks by osyoyu

Other Decks in Programming

Transcript

  1. Daisuke Aritomo (@osyoyu) / Kaigi on Rails 2022 ྡͷ API

    ͷσʔλΛ Rails Β͘͠ɺ͠ͳ΍͔ʹѻ͏
  2. ͲͷΑ͏ͳ Ruby ΠϯλʔϑΣʔεʹ͢Δ͔ʁ Ϩγϐίϯςετͷ microservice ͷྫ User (MySQL) Recipe 


    Contest (MySQL) Recipe (API) Recipe 
 ContestEntry (MySQL) N 1 N 1 N 1 1 1
  3. • ҟͳΔιʔεछผͷ en ti ty ͸ 
 ҟͳΔऔಘํࣜΛఏڙ͢Δ • MySQL

    ༝དྷ͸ AR::Base Λ 
 ܧঝ͢ΔΫϥεͰදݱ • ֎෦༝དྷ͸ผͷΫϥεͰදݱ 
 (i.e. AR::Base Λܧঝ͠ͳ͍) (1) ιʔεͷछผʹண໨͢Δ User (MySQL) Recipe 
 Contest (MySQL) Recipe (API) Recipe 
 ContestEntry (MySQL) N 1 N 1 N 1 1 1
  4. • ಉҰͷυϝΠϯͷ en ti ty ͸ 
 ಉҰͷऔಘํ๏Λఏڙ͢Δ • ΞϓϦͷυϝΠϯ্ͳΒ͹

    
 ͢΂ͯ Ac ti veRecord-like ͳ 
 औಘํࣜΛఏڙ͢Δ (2) υϝΠϯڥքʹண໨͢Δ Tweet (API) User (MySQL) Recipe 
 Contest (MySQL) Recipe (API) Recipe 
 ContestEntry (MySQL) 1 N 1 N 1 1
  5. ਓྨͷྺ࢙: ActiveResource, Her, ... • Ac ti veResource • RESTful

    API Λ͍͍ײ͡ʹ model ͬΆͯ͘͘͠ΕΔ • Rails 3.2 ·Ͱͷඪ४ػೳͩͬͨ • Her • ͜Ε΋ಉ͡Α͏ͳ໨తͷ Gem • ΄͔ʹ΋ Ac ti veRestClient, Spyke, Flexirest ͳͲ͕͋Δ
  6. ਓྨͷྺ࢙: ActiveResource, Her, ... • ͜ΕΒ͸ "Res tf ul API"

    Λେલఏʹ͓͍͍ͯΔ • ಛఆͷ URL ߏ଄ΛٻΊΒΕΔ • ΍ͬͺΓ JOIN ͸ͦ͜·ͰಘҙͰ΋ͳ͍
  7. AR ෩ API ΫϥΠΞϯτΛͭͬͯ͘ΈΑ͏ • ֎෦ API ͕ఏڙ͢Δ Recipe ʹ͍ͭͯ

    • Recipe. fi nd(1) ͷΑ͏ͳܗͰΫΤϦͰ͖Δ • @recipe. ti tle ͷΑ͏ͳܗͰϑΟʔϧυΛಡΊΔ • Ϧιʔεαʔόʔʹಛఆͷߏ଄ (RESTful) Λཁٻ͠ͳ͍ • JOIN (has_many, belongs_to, ...) ΋͏·͘͜ͳͤΔ • Α͏ͳʢجຊతͳʣ΋ͷΛͭͬͯ͘ΈΑ͏
  8. • Recipe. fi nd ͷ಺෦ͰΩϡʔΠϯά͢Δ • Recipe. fi nd ͔Β͸ͻͱ·ͣ

    Promise తͳΦϒδΣΫτ͕ฦΔ • exAspArk/batch-loader Λར༻ • Recipe. fi nd ͷฦΓ஋ʹରͯ͠ # ti tle ͳͲΛݺͿͱɺอཹ͞Ε͍ͯͨϦΫΤετ͕·ͱΊͯඈͿ BatchLoader Ͱ eager loading ͢Δ Level 2
  9. API ΋ຊ෺ͷ ActiveRecord ʹͪ͠Ό͏ Level 3 • ຊ෺ͷ Ac ti

    veRecord Ϋϥεʹͯ͠͠·͏ 
 ͜ͱͰ has_many, belongs_to ͳͲ͕࢖͑Δ • ͜ͷٕΛ࢖͑Δ͔͸ෆม৚݅࣍ୈ • ͜͜Ͱ͸ "recipe.user_id ͕ෆมͰ͋Δ" • (͔ͭ recipe.user_id ͕ FK Ͱ͋Δ͜ͱ) • ෆม৚݅ͷ෦෼͚ͩςʔϒϧʹೖΕΔ
  10. • ݸਓతʹ͸ AR ෩Ͱ͸ͳ͘ɺ΋ͬͱૢ࡞తͳܗ͕ྑ͍ͱࢥ͏ • APIClient.update(id: 1, {name: "nanika"}) •

    τϥϯβΫγϣϯ͕ඞཁͳΒ1ͭͷDB΁ͷ౷߹Λߟ͑Δ΂͖ • ΫϥΠΞϯτͷߏ଄ʹؔ܎ͳ͘ɺ෼͞ΜτϥϯβΫγϣϯ͸ࠔ೉ ͱ͜ΖͰߋ৽ɾ࡟আ͸ʁ Others
  11. མͪึͻΖ͍ɾࡉ͔͍࿩ Others • AR ෩ͷΦϒδΣΫτΛ༻ҙ͢ΔʹͤΑɺescape hatch ͸༻ҙͨ͠΄͏͕͍͍ • Ac ti

    veModel::Model ʹ͍ͭͯ • ͓޷ΈͰ include ͢ΔͱΑ͍Ͱ͠ΐ͏ • valida ti on ΍ callbacks, rou ti ng ͳͲʹؔ࿈͢Δαϙʔτ͕͍͖ͭͯ·͢ • cookpad/expeditor ͰߋͳΔߴ଎ԽΛૂ͏