Thuta Learning
ရှာဖွေရန်
GraphQL
ProjectsWeb Developmentbeginner

Project 3 — Blog API ကို Auth နှင့် Rate Limiting ထည့်ခြင်း

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Project 3 — Blog API ကို Auth နှင့် Rate Limiting ထည့်ခြင်း concept ကို နားလည်ရှင်းပြနိုင်ရန်
  • နမူနာ GraphQL query/code ကို ကိုယ်တိုင် run ပြီး output စစ်နိုင်ရန်
  • Tutorial Platform project နှင့် production scenario တွင် မှန်ကန်စွာအသုံးချနိုင်ရန်

နားလည်ထားရမယ့် အချက်

Project 1 ကနေ ဆောက်ထားတဲ့ Blog API ကို production-ready ဖြစ်အောင် authentication layer (context ထဲ token decode) နှင့် per-user rate limit (mutation တစ်ခုချင်းအတွက် window-based counter) ထည့်ပေါင်းမယ်—lesson 16/17 ရဲ့ context/authorization pattern နှင့် lesson 20 ရဲ့ abuse-prevention idea ကို project တစ်ခုအဖြစ် ပေါင်းစည်းသုံးမှာဖြစ်ပါတယ်။ Rate limit check ကို resolver-level middleware/wrapper function အဖြစ် reusable ဖြစ်အောင် ဆောက်ရပါတယ်။

လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်

`createPost` mutation ကို `requireAuth(context)` ဖြင့် login state စစ်ပြီး `checkRateLimit` helper ဖြင့် user တစ်ဦးကို hour တစ်ခုအတွင်း post 5 ခုသာ ကန့်သတ်မယ်။ Limit ကျော်ရင် `TOO_MANY_REQUESTS` extension code ပါသော error ပြန်ပေးမယ်—frontend က retry-after message ပြသနိုင်ဖို့ပါ။

အတူတူ စမ်းရေးကြည့်မယ်

typescript
const resolvers = {
  Mutation: {
    createPost: async (
      _parent: unknown,
      args: PostInput,
      context: Context,
    ) => {
      requireAuth(context);
      await checkRateLimit(`post:create:${context.userId}`, {
        max: 5,
        windowSeconds: 3600,
      });
      return context.db.post.create({
        data: { ...args, authorId: context.userId },
      });
    },
  },
};
You should see
Blog API ကို auth-protected + rate-limited mutation ဖြင့် production-facing service အဖြစ် ဆောင်ရွက်နိုင်မည်။

၅ မိနစ် စမ်းကြည့်

`addComment` mutation ကိုပါ auth+rate limit (ဥပမာ user တစ်ဦး comment 20 ခု/hour) ထည့်ပါ။

သတိလေးတစ်ချက်

Rate limit counter ကို process-local memory (plain JavaScript object/Map) ထဲသာ ထားရင် server instance အများနဲ့ run တဲ့အခါ limit ကို instance တစ်ခုချင်းစီက သီးခြားရေတွက်နေလို့ real limit ထက် ပိုများ requests ဝင်နိုင်ပါတယ်—shared store (Redis) လိုပါတယ်။

Apollo Server — Authentication and AuthorizationGraphQL

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Rate limit counter ကို process-local memory (plain JavaScript object/Map) ထဲသာ ထားရင် server instance အများနဲ့ run တဲ့အခါ limit ကို instance တစ်ခုချင်းစီက သီးခြားရေတွက်နေလို့ real limit ထက် ပိုများ requests ဝင်နိုင်ပါတယ်—shared store (Redis) လိုပါတယ်။
  • နမူနာ query/mutation ကို production API ပေါ် တိုက်ရိုက်မစမ်းဘဲ local/test server နှင့် recoverable data ပေါ်တွင် အရင်အတည်ပြုပါ။

လေ့ကျင့်ခန်း

`addComment` mutation ကိုပါ auth+rate limit (ဥပမာ user တစ်ဦး comment 20 ခု/hour) ထည့်ပါ။

You'll know it worked when: Blog API ကို auth-protected + rate-limited mutation ဖြင့် production-facing service အဖြစ် ဆောင်ရွက်နိုင်မည်။

Project 3 — Blog API ကို Auth နှင့် Rate Limiting ထည့်ခြင်း | Thuta Learning