Skip to content

API Realization: REST Resources & Constraints, API Management, GraphQL Schemas ​

"Define a protocol that gives access to your subsystem as a set of services. Open the protocol so that all who need to integrate with you can use it." — Eric Evans, Domain-Driven Design Reference (2015), Open Host Service

خلاصه (Summary): یک «context محدود (Bounded Context)» وقتی برای دیگران قابل استفاده می‌شود که مدلش به یک API منتشرشده تبدیل شود: یک «سرویس میزبان باز (Open Host Service)» که منابع، فرمان‌ها و شکل خطاهایش یک «زبان منتشرشده (Published Language)» می‌سازند؛ زبانی کوچک‌تر و پایدارتر از مدل داخلی. REST و GraphQL دو راه برای پیاده‌سازی همین یک زبان‌اند؛ هیچ‌کدام خودِ زبان نیستند. تمرکز (Focus): چه چیزی را نشان بدهیم و چه چیزی را پنهان نگه داریم، «منبع (Resource)» در برابر aggregate و جدول، endpointهای «وظیفه‌محور (Task-based)»، معناشناسی HTTP به‌عنوان قید (متدها، idempotency، status code، ETag، If-Match، RFC 9457)، نشان دادن «سازگاری نهایی (Eventual Consistency)» با 202 Accepted، pagination، نسخه‌بندی، OpenAPI قرارداد-اول، API management، طراحی schema در GraphQL (input type، payload، connection، dataloader، federation)، امنیت لبهٔ API و تست قرارداد، با context فروش (Sales) در Go و Laravel. هدف یادگیری (Learning goal): aggregate Order در context فروش را دو بار منتشر کنید، یک بار به‌صورت REST و یک بار به‌صورت schema در GraphQL؛ با endpointهای وظیفه‌محور، Problem Details، درخواست‌های شرطی، لغو ناهمگام قابل‌مشاهده، جست‌وجوی دسته‌ای محصول و تست؛ و برای هر انتخاب طراحی بگویید کدام بخش مدل را محافظت می‌کند.

این فصل در گروه DD 03 (داده و API در میکروسرویس‌ها) است و فرض می‌کند Bounded Context (مرز کجاست)، Aggregates & Factories (پشت مرز چه هست) و Context Maps & Integration Patterns (API به کدام رابطه خدمت می‌کند) را خوانده‌اید. فقط یک پرسش را جواب می‌دهد: یک context چطور مدلش را به API‌ای تبدیل کند که دیگران بتوانند به آن تکیه کنند؟ بقیه با همسایه‌هاست. هنر عمومی طراحی API روی HTTP در REST API Design، GraphQL، gRPC & Protobuf و API Versioning است؛ gateway، BFF و mesh در API Gateway, BFF & Service Mesh؛ ارتباط سرویس‌ها در Service Communication؛ سرویس‌های پشت endpointها در Domain, Application & Infrastructure Services؛ وضعیت ذخیره‌شده در Repositories؛ رویدادها در Domain Events vs Integration Events و Outbox Pattern؛ keyset pagination در Pagination؛ ستون version در Optimistic vs Pessimistic Locking.

نقشهٔ صفحه (Page map) ​

دنبال چه هستیدبروید به
کل فصل در چند جدولهمه‌چیز در یک دقیقه
چرا API فقط مدل سریالایزشده نیستچرا وجود دارد
Fielding، Evans، Richardson، RFC 9457، GraphQLاز کجا آمده
API در زبان DDD چیستOHS و Published Language
منبع نه aggregate است نه جدولمنبع در برابر aggregate
POST /orders/{id}/placement یا PATCH statusوظیفه‌محور یا CRUD
متدها، safe، idempotent، status codeمعناشناسی HTTP
ETag، If-Match، 304، 412، 428درخواست‌های شرطی
بدنهٔ خطاProblem Details
202 و Location و منبع وضعیتسازگاری نهایی در API
لینک‌ها، سطوح Richardson، JSON:APIHypermedia
cursor، فیلتر، مرتب‌سازیPagination و فیلتر و sort
تغییر افزایشی، Sunset، Deprecationنسخه‌بندی زبان منتشرشده
OpenAPI، Spectral، کلاینت تولیدشدهقرارداد-اول
کلید، سهمیه، پورتال توسعه‌دهندهAPI management
SDL، typeهایی از مدلschema در GraphQL
mutation، input type، payload، userErrorsفرمان و خطا در GraphQL
Relay connectionpagination در GraphQL
N+1، dataloader، Lighthouse، gqlgenN+1 و dataloader
Federation و BFFFederation و BFF
gRPC، webhook، AsyncAPIپیاده‌سازی‌های دیگر
authn، scope، tenant isolationامنیت لبه
contract test، Spectral، CDCتست
کد Go و LaravelGo، Laravel
هر context و هر سرویسدر معماری
عملیآزمایشگاه
باورهای غلط، چکیده، آزمون، واژه‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

همه‌چیز در یک دقیقه ​

واژگان. هر ردیف بعداً در فهرست مفاهیم باز می‌شود.

اصطلاحبه زبان سادهمثال کوچکبدون آن چه می‌شود
Open Host Service (OHS)یک پروتکل باز برای همهٔ کسانی که با context یکپارچه می‌شوندHTTP API فروشبرای هر مصرف‌کننده یک مترجم سفارشی
Published Language (PL)مدل مستندشدهٔ آن پروتکل، جدا از مدل داخلیJSON سفارش، فایل OpenAPIمدل داخلی نشت می‌کند و یخ می‌زند
Resourceچیزی نام‌پذیر که می‌شود آدرس داد و نمایشش را گرفت/orders/o1endpointهایی به نام تابع و جدول
Representationبایت‌هایی که در یک لحظه برای یک منبع فرستاده می‌شودJSON سفارش همراه ETagکلاینت به ستون‌های ذخیره‌سازی وابسته می‌شود
Task-based endpointفرمانی با زبان کسب‌وکارPOST /orders/o1/placementPATCH status اجازهٔ دور زدن قاعده را می‌دهد
Idempotentتکرار درخواست اثری برابر یک بار ارسال داردPUT، DELETE، POST با Idempotency-Keyretry دو بار شارژ می‌کند
Conditional requestدرخواستی که فقط اگر نسخهٔ کلاینت به‌روز باشد موفق می‌شودIf-Match: W/"2"Lost update روی HTTP
Problem Detailsیک شکل ماشین‌خوان برای خطاapplication/problem+jsonهر endpoint خطای خودش را می‌سازد
Eventual consistency قابل‌مشاهدهAPI می‌گوید «پذیرفته شد، تمام نشده» و جای تماشا می‌دهد202 + Locationکلاینت فکر می‌کند تغییرِ در انتظار قطعی است
Keyset cursorنشانگر مات برای صفحهٔ بعدnextCursorصفحه‌های offset ردیف جا می‌اندازند یا تکرار می‌کنند
Contract-firstفایل OpenAPI/SDL قبل از کد نوشته و بازبینی می‌شودsales.openapi.yamlقرارداد همان است که کد اتفاقاً انجام می‌دهد
API gatewayدرِ جلویی: احراز هویت، سهمیه، مسیریابی، تحلیلKong، Apigeeهر سرویس قواعد مشترک را دوباره می‌نویسد
GraphQL schemaزبان منتشرشدهٔ تایپ‌دار برای کلاینت‌های GraphQLtype Order { ... }over/under-fetching یا schema‌ای که آینهٔ جدول‌هاست
Dataloaderکلیدها را در یک سطح اجرا جمع می‌کند و یک‌جا می‌گیردجست‌وجوی Product برای هر خطN+1 فراخوانی به Catalog

دو پیاده‌سازی از یک زبان.

پرسشRESTGraphQL
واحد قراردادیک resource و یک methodیک field در گراف typeها
شکل پاسخ را چه کسی می‌دهدسرور (representation)کلاینت (selection set)
فرمان چه شکلی داردPOST /orders/{id}/placementmutation { placeOrder(input: ...) }
شکست کسب‌وکاری409 / 422 با application/problem+jsonuserErrors در payload، HTTP 200
کشکش HTTP، ETag، 304کش کلاینت با id، persisted query؛ CDN سخت‌تر
صفحه‌بندیlimit + cursorconnection با first + after
بهترین کاربردچند مصرف‌کنندهٔ پایدار؛ فرمان؛ خواندن کش‌پذیرکلاینت‌های زیاد، نمای متنوع، تجمیع بین contextها
بزرگ‌ترین تلهCRUD روی جدول‌هاN+1 و queryهای بی‌حد

قرارداد HTTP در یک جدول (هر ردیف در معناشناسی HTTP و سازوکار باز می‌شود).

وضعیتStatusچه چیزی اضافه شود
پیش‌نویس ساخته شد201 CreatedLocation، ETag
خواندن، بدون تغییر304 Not ModifiedETag
فرمان پذیرفته شد، کار ادامه دارد202 AcceptedLocation، Retry-After
قاعدهٔ کسب‌وکار نه می‌گوید، تعارض وضعیت409 Conflictنوع Problem
ورودی درست‌ساخت اما نامعتبر422 Unprocessable Contenterrors[].pointer
نسخهٔ کهنه412 Precondition Failedنوع Problem
هدر شرطی غایب428 Precondition Requiredنوع Problem
درخواست زیاد429 Too Many RequestsRetry-After

چرا وجود دارد ​

«context محدود» ذاتاً خصوصی است. داخلش مدل می‌تواند غنی باشد، هفته‌ای عوض شود و واژه‌هایی داشته باشد که بیرونی‌ها نمی‌فهمند. بیرون، تیم‌ها و شرکت‌های دیگر هنوز باید بپرسند و فرمان بدهند. API جایی است که این دو دنیا به هم می‌رسند و تصمیم اصلی این است: چقدر از داخل را نشان بدهیم؟

مدل را مستقیم نشان بدهیمیک زبان منتشر کنیم
ساختن سریع: entity را serialize کنبه لایهٔ نگاشت و فایل قرارداد نیاز دارد
هر refactor یک مصرف‌کننده را می‌شکندrefactorها پشت نگاشت می‌مانند
نام جدول و کلاس واژهٔ عمومی می‌شودواژه‌های عمومی از زبان فراگیر (Ubiquitous Language) می‌آیند
قاعده دور زده می‌شود (PATCH status)قاعده پشت فرمان نام‌دار است
نیاز یک مصرف‌کننده شکل API همه را تعیین می‌کندزبان به مجموعهٔ مصرف‌کننده‌ها خدمت می‌کند

تشبیهی که در این صفحه تکرار می‌کنیم: رستوران. آشپزخانه (context) ایستگاه، دستور پخت و قاعدهٔ انبار دارد. مهمان‌ها اینها را نمی‌بینند؛ منو (زبان منتشرشده)، گارسون (API) و چند قاعدهٔ خانه («آشپزخانه ساعت ده می‌بندد») را می‌بینند. منویی که قفسه‌های یخچال را فهرست کند مدلِ نشت‌کرده است. منویی که بگوید «هرچه خواستید از گارسون بپرسید» قابل‌استفاده نیست. REST منوی چاپی با غذاهای ثابت است؛ GraphQL کاسهٔ «خودت بساز» با فهرست ثابت مواد؛ آشپزخانه یکی است.

سه بدفهمی، همین اول ​

  1. «REST یعنی CRUD روی جدول.» منبع در تعریف Fielding «هر اطلاعاتی است که بتوان نامش برد» نه یک ردیف. placement یا cancellation-request منبع کاملاً درستی است (به منبع در برابر aggregate نگاه کنید).
  2. «GraphQL جای REST را می‌گیرد.» GraphQL پیاده‌سازی دیگری از همان زبان منتشرشده است؛ برای خواندنِ چندکلاینتی بهتر و برای کش و سطح پر از فرمان ضعیف‌تر (به انتخاب).
  3. «API جزئیات پیاده‌سازی سرویس است.» گران‌ترین چیزی است که در کل سیستم می‌شود عوض کرد، چون کد دیگران به آن وابسته است. برای همین مثل یک محصول طراحی، بازبینی و نسخه‌بندی می‌شود.

از کجا آمده ​

سالمنبعچه چیزی به این فصل داد
2000Roy Fielding، پایان‌نامه، فصل 5، Representational State Transferچهار قید رابط، منبع و نمایش
2003Eric Evans، Domain-Driven DesignOpen Host Service و Published Language (خلاصه در DDD Reference رایگان 2015)
2010Martin Fowler، Richardson Maturity Model (18 مارس 2010)سطح 0 تا 3: منبع، فعل، hypermedia
2013Vaughn Vernon، Implementing DDD، فصل 4معماری یک context و یکپارچگی RESTful (کتاب؛ دریافت نشد؛ چیزی نقل نشده)
2012 / 2015GraphQL «originally created at Facebook in 2012»؛ «The development of this open standard started in 2015» (مقدمهٔ spec؛ ویرایش October 2021)queryهای تایپ‌دار با شکل کلاینت
2021OpenAPI 3.1.0 (15 فوریهٔ 2021)هم‌ترازی با JSON Schema 2020-12، قالب قرارداد
2023RFC 9457 Problem Details for HTTP APIs (جولای 2023؛ جایگزین RFC 7807)یک قالب خطا
ادامه‌دارراهنماهای API در Zalando، Microsoft و Googleقراردادهای عملی: API First، long-running operation، custom method

Fielding قیدی را نام می‌برد که این فصل مدام به آن برمی‌گردد: «REST is defined by four interface constraints: identification of resources; manipulation of resources through representations; self-descriptive messages; and, hypermedia as the engine of application state.» و صادقانه هزینه را هم می‌گوید: «The trade-off, though, is that a uniform interface degrades efficiency, since information is transferred in a standardized form rather than one which is specific to an application's needs.» GraphQL تا حد زیادی برای پس‌گرفتن همین کارایی ساخته شد، و خواهیم دید چه هزینه‌ای دارد.

Evans نیمهٔ DDD را اضافه می‌کند. دربارهٔ Published Language: «If one is used as a data interchange language, it essentially becomes frozen and cannot respond to new development needs.» دلیل وجود این فصل همین جمله است: مدل دامنه را مستقیم نشان بدهید و دیگر هرگز نمی‌توانید refactor کنید.

Fowler دربارهٔ سطح 2 می‌نویسد: «Level 2 moves away from this, using the HTTP verbs as closely as possible to how they are used in HTTP itself.» و سطح 3 را «ugly acronym» یعنی HATEOAS می‌نامد. سطح 3 ابزار است، نه نشان افتخار (به Hypermedia).

فصل 4 Vernon فقط پس‌زمینه است؛ متنش دریافت نشد و هیچ جمله‌ای از آن نقل نشده.

واقعاً دربارهٔ چیست ​

API روی زمین، چهرهٔ زمان اجرای دو الگوی context map است (تعریف کامل در Context Maps & Integration Patterns):

  • Open Host Service: Sales یک پروتکل، «a set of services»، را به همهٔ downstreamها می‌دهد، نه یک مترجم برای هر مصرف‌کننده. Evans می‌گوید این provider را در موقعیت upstream می‌گذارد و «typically some of them will be conformist and some will build anticorruption layers».
  • Published Language: قالب آن پروتکل مستند است و مدل داخلی نیست. فایل OpenAPI، SDL در GraphQL و JSON Schemaی رویدادها با هم زبان منتشرشده‌اند.
Sales context (private)Order aggregateinvariants, state machineApplication servicesplace, cancel, add lineTables, ORM, eventsfree to change weeklyPublished languagesmaller than the model, stableResources + commandsorder, line, placementContract documentsOpenAPI, SDL, schemasOpen Host Service owns it,semantic versioningREST APIresources, HTTP verbsETag, 202, Problemcacheable readsGraphQL APIone schema, many viewspayload + userErrorsdataloader batchingAPI gatewayauth, quotas, keysrouting, analyticsConsumersweb, mobile, partnersBilling, Fulfilment(if they call at all)translaterealiserealiseThe API is shaped by what consumers need to know, not by how Sales stores it.

سه نتیجه همهٔ بخش‌های بعدی را می‌راند.

  1. API مدل مستقل خودش را دارد. اسم، وضعیت و قول پایداری خودش را دارد. از مدل دامنه مشتق می‌شود اما کوچک‌تر و پایدارتر است؛ به منبع در برابر aggregate.
  2. API تنها درِ aggregate برای بیرونی‌هاست. هر فرمان از application service و بعد متدهای aggregate می‌گذرد (به Domain, Application & Infrastructure Services). APIای که مستقیم روی جدول می‌نویسد invariantها را دور می‌زند.
  3. بیش از یک در هست. REST، GraphQL، gRPC، رویداد و webhook پیاده‌سازی‌های یک زبان‌اند. نام‌گذاری، کد خطا و نسخه باید بینشان هماهنگ بماند. در کد این فصل هر دو، REST و GraphQL، همان Service را صدا می‌زنند.
لایهمالک چیستچه وقت عوض می‌شود
مدل دامنه (Order)Invariant و state machineقاعدهٔ کسب‌وکار عوض شود
Application service (Service)use caseها، تراکنش، portهایک use case عوض شود
زبان منتشرشده (OpenAPI + SDL)منابع، فرمان‌ها، خطاها، scopeهاقولی که مصرف‌کننده می‌بیند عوض شود (نادر، نسخه‌دار)
پیاده‌سازی (handler، resolver)مکانیک HTTP و GraphQLانتقال عوض شود
Gatewayکلید، سهمیه، مسیریابی، تحلیلسیاست عوض شود

فهرست مفاهیم ​

Open Host Service و Published Language در عمل حیاتی ​

به زبان ساده: تصمیم بگیرید context چه قولی به دنیای بیرون می‌دهد، آن را در یک سند بنویسید و بقیه را خصوصی نگه دارید.

بدفهمی رایج: «اگر فیلدی روی aggregate هست، شاید مصرف‌کننده بخواهدش؛ پس نشانش بده.» هر فیلد نمایش‌داده‌شده یک قول است. آنچه مصرف‌کننده باید بداند و می‌تواند به آن تکیه کند منتشر کنید؛ بقیه (شمارندهٔ version، ستون‌های audit، قاعدهٔ قیمت داخلی) داخل می‌ماند.

تعریف: زبان منتشرشدهٔ یک context مجموعهٔ منابع، فرمان‌ها، رویدادها، نوع خطاها و scopeهایی است که API مستند می‌کند. فیلد فقط وقتی به آن می‌رسد که زبان فراگیر نامش را ببرد و تیم آماده باشد تا پایان عمر آن نسخه نگهش دارد.

Decision per field of the Order aggregate
1  customer id         -> published (consumers filter by it)
2  status              -> published as a read-only state; changed only by commands
3  lines               -> published as sub-resource and embedded summary
4  total               -> published, derived on read, never accepted as input
5  version             -> published as ETag, not as a field
6  internal discount rule, audit columns, row id -> private

سناریوی واقعی: Billing می‌خواهد بداند «این سفارش چقدر است و مال کیست». خط‌ها، کد تخفیف و وضعیت picking را لازم ندارد. Fulfilment خط‌ها و آدرس را می‌خواهد اما روش پرداخت را نه. وب برای یک صفحه همه‌چیز می‌خواهد. یک زبان، سه نیاز: دلیلی برای منبع‌های باریک با قاعدهٔ embedding (REST) یا انتخاب کلاینت (GraphQL).

چه چیزی این را فراهم می‌کند:

سازوکارنقشکجای این فصل
DTO / API Resourceلایهٔ نگاشت، یک کلاس برای هر شکل منتشرشدهOrderDTO در Go، OrderResource در Laravel
OpenAPI / SDLقرارداد مکتوبقرارداد-اول
فهرست خطاهانوع و کد پایدارProblem Details
Scopeهاچه کسی چه کاری بکندامنیت لبه
سیاست نسخه‌بندیچه چیزی بدون نسخهٔ جدید عوض می‌شودنسخه‌بندی

منبع در برابر aggregate در برابر جدول حیاتی ​

به زبان ساده: منبع چیزی است که کلاینت می‌تواند نامش را ببرد و دربارهٔ آن بپرسد. aggregate مرز سازگاری در کد شماست. جدول شیوهٔ ذخیره است. این سه به هم مربوط‌اند و یکی نیستند.

بدفهمی رایج: «یک جدول، یک aggregate، یک endpoint.» نگاشت چندبه‌چند است: یک aggregate می‌تواند چند منبع باشد، چند aggregate می‌تواند یک منبع بسازد و بعضی منابع (درخواست لغو، گزارش، جست‌وجو) اصلاً aggregate ندارند.

تعریف: Fielding: «Any information that can be named can be a resource: a document or image, a temporal service (e.g. "today's weather in Los Angeles"), a collection of other resources, a non-virtual object (e.g. a person), and so on.» AIP-121 گوگل قاعدهٔ کار را اضافه می‌کند: «The fundamental building blocks of an API are individually-named resources (nouns) and the relationships and hierarchy that exist between them.»

Aggregate (inside Sales)Order (root)status, customer, currencyOrderLine (entity)Never publishedpricing rule, row version, auditResources (the published language)GET /orders/{id}a representation of the order, with ETagPOST /orders/{id}/linessub-resource collection, price from CatalogPOST /orders/{id}/placementa command named as a noun; If-Match requiredPOST /orders/{id}/cancellation-requestscreates a status resource, answers 202GET /cancellation-requests/{id}no aggregate behind it: a workflow recordOne aggregate, several resources.Some resources have no aggregate.Nothing here is a table name.
Mapping for the Sales running example
Aggregate / record          Resource (URI)                           Why a resource
Order (root)                /orders/{id}                             the thing consumers name
OrderLine (inside)          /orders/{id}/lines (sub-resource)        add a line; no URI per line needed yet
Order.Place() (a command)   /orders/{id}/placement                   a noun for an event-like command
(no aggregate: workflow)    /cancellation-requests/{id}              a status the client can poll
Order list (a query)        /orders?status=placed&limit=20           a collection with filters

سناریوهای واقعی: (1) aggregate Customer به‌صورت /customers/{id} و /customers/{id}/addresses منتشر می‌شود، چون کلاینت‌ها آدرس را جدا نام می‌برند. (2) گزارش «سفارش در هر روز» منبع /reports/daily-orders است که روی یک read model سوار است نه aggregate Order (به Data Patterns). (3) import دسته‌ای منبع /imports/{id} با یک وضعیت است، نه یک POST طولانی.

چه چیزی در representation می‌آید: فقط دادهٔ داخل مرز aggregate و مدل منتشرشده. دادهٔ context دیگر (نام محصول از Catalog) یا با id و لینک ارجاع می‌شود، یا با تصمیم صریح و یادداشت تازگی embed می‌شود.

راه‌حل / نحوهٔ استفاده: برای هر شکل منتشرشده یک DTO. هرگز json.Marshal(order) یا return $order از controller.

go
package rest

import (
	"fmt"
	"strconv"
	"strings"
	"time"

	"academy/api-realization-rest-graphql/sales"
)

// MoneyDTO is the published money shape: minor units plus currency.
type MoneyDTO struct {
	AmountMinor int64  `json:"amountMinor"`
	Currency    string `json:"currency"`
}

// LineDTO is one line of the order representation.
type LineDTO struct {
	SKU       string   `json:"sku"`
	Quantity  int      `json:"quantity"`
	UnitPrice MoneyDTO `json:"unitPrice"`
}

// Link is a hypermedia control: where to go and which method to use.
type Link struct {
	Href   string `json:"href"`
	Method string `json:"method,omitempty"`
}

// OrderDTO is the representation of the Order resource. It is shaped by the
// published language, not by the aggregate's fields.
type OrderDTO struct {
	ID         string          `json:"id"`
	CustomerID string          `json:"customerId"`
	Status     string          `json:"status"`
	Lines      []LineDTO       `json:"lines"`
	Total      MoneyDTO        `json:"total"`
	PlacedAt   *time.Time      `json:"placedAt,omitempty"`
	Links      map[string]Link `json:"_links"`
}

// CancellationDTO is the status resource for a cancellation request.
type CancellationDTO struct {
	ID      string          `json:"id"`
	OrderID string          `json:"orderId"`
	State   string          `json:"state"`
	Reason  string          `json:"reason"`
	Detail  string          `json:"detail,omitempty"`
	Links   map[string]Link `json:"_links"`
}

// OrderPage is a keyset-paginated collection.
type OrderPage struct {
	Items      []OrderDTO `json:"items"`
	NextCursor string     `json:"nextCursor,omitempty"`
}

func toOrderDTO(o *sales.Order) OrderDTO {
	id := string(o.ID())
	d := OrderDTO{
		ID: id, CustomerID: string(o.Customer()), Status: string(o.Status()),
		Lines: []LineDTO{}, Total: MoneyDTO{o.Total().Minor, o.Total().Currency},
		Links: map[string]Link{"self": {Href: "/orders/" + id}},
	}
	for _, l := range o.Lines() {
		d.Lines = append(d.Lines, LineDTO{SKU: string(l.SKU), Quantity: l.Quantity,
			UnitPrice: MoneyDTO{l.UnitPriceMinor, o.Currency()}})
	}
	if !o.PlacedAt().IsZero() {
		t := o.PlacedAt()
		d.PlacedAt = &t
	}
	// Links advertise only the transitions the state machine allows now.
	switch o.Status() {
	case sales.Draft:
		d.Links["add-line"] = Link{Href: "/orders/" + id + "/lines", Method: "POST"}
		d.Links["placement"] = Link{Href: "/orders/" + id + "/placement", Method: "POST"}
	case sales.Placed:
		d.Links["cancellation-requests"] = Link{Href: "/orders/" + id + "/cancellation-requests", Method: "POST"}
	}
	return d
}

func toCancellationDTO(r sales.CancellationRequest) CancellationDTO {
	d := CancellationDTO{ID: r.ID, OrderID: string(r.OrderID), State: string(r.State), Reason: r.Reason, Detail: r.Detail,
		Links: map[string]Link{"self": {Href: "/cancellation-requests/" + r.ID}}}
	if r.State != sales.CancellationPending {
		d.Links["order"] = Link{Href: "/orders/" + string(r.OrderID)}
	}
	return d
}

// etag is a weak validator derived from the aggregate version.
func etag(o *sales.Order) string { return fmt.Sprintf(`W/"%d"`, o.Version()) }

// parseETag turns W/"3" (or "3") into 3; ok is false when the header is malformed.
func parseETag(h string) (int, bool) {
	h = strings.TrimPrefix(strings.TrimSpace(h), "W/")
	n, err := strconv.Atoi(strings.Trim(h, `"`))
	return n, err == nil && n > 0
}

وظیفه‌محور در برابر CRUD: فرمان به‌عنوان قصد حیاتی ​

به زبان ساده: کار را همان‌طور که کسب‌وکار می‌گوید نام ببرید («سفارش را ثبت کن»، «درخواست لغو بده») نه «فیلد status را عوض کن».

بدفهمی رایج: «PATCH /orders/{id} با {"status":"placed"} RESTful‌تر است.» عمومی‌تر است، و عمومی بودن همان مشکل است: هر کلاینتی هر گذاری را امتحان می‌کند، قاعده در ذهن همهٔ کلاینت‌ها می‌ماند و audit می‌گوید «status عوض شد» نه «مشتری سفارش را ثبت کرد».

تعریف: API وظیفه‌محور فرمان‌ها را به‌صورت قصد نشان می‌دهد. AIP-136 گوگل دلیلش را می‌گوید: custom methodها «provide a means for an API's vocabulary to adhere to user intent» و «should only be used for functionality that can not be easily expressed via standard methods». در HTTP معمولاً یعنی یک POST به اسمی که نتیجه یا فرایند را نام می‌برد: /placement، /cancellation-requests، /refunds.

CRUD style (state is a free-for-all)          Task-based style (state is a protocol)
1  PATCH /orders/o1 {"status":"placed"}        1  POST /orders/o1/lines        {sku, qty}
2  PATCH /orders/o1 {"status":"draft"}   <-    2  POST /orders/o1/placement    If-Match: W/"2"
3  PATCH /orders/o1 {"total": 1}               3  POST /orders/o1/cancellation-requests
   -- invariants live in every client             -- invariants live in the aggregate
جنبهCRUD روی فیلدهاوظیفه‌محور
قاعده‌هادر کلاینت‌ها یا validator پنهاندر aggregate پشت یک متد نام‌دار
Audit«status عوض شد»«سفارش توسط مشتری c1 ثبت شد»
تکاملstateهای جدید همهٔ کلاینت‌ها را می‌شکنندفرمان جدید = URI جدید، قدیمی‌ها می‌مانند
مجوزسطح فیلد، دست‌وپاگیرسطح فرمان و scope: orders:write
کشف‌پذیریمستندات را بخوانلینک‌ها فرمان‌های مجاز را اعلام می‌کنند (به Hypermedia)
مناسب برایابزار admin، تنظیمات، دادهٔ سادهزیردامنه‌های هسته با قاعدهٔ واقعی

سناریوهای واقعی: capture پرداخت، ثبت سفارش، ارسال بار، تخصیص نقش، بستن حساب. در زیردامنهٔ پشتیبان (ویژگی‌های Catalog، پروفایل Identity) CRUD ساده کافی و ارزان‌تر است؛ دسته‌بندی Domains & Subdomains می‌گوید endpoint وظیفه‌محور کجا ارزش دارد.

راه‌حل: در کد، برای هر فرمان یک handler که یک متد application service را صدا می‌زند. handler هیچ قاعده‌ای ندارد.

معناشناسی HTTP به‌عنوان قید حیاتی ​

به زبان ساده: متد و status code تزئین نیستند؛ proxy، مرورگر، retry و gateway روی آنها عمل می‌کنند. همان‌طور که تعریف شده‌اند به‌کار ببریدشان.

بدفهمی رایج: «POST برای هر چیزی که داده را عوض می‌کند و 200 OK برای هر چیزی که کار کرد.» retry، کش و کلاینت با متدها متفاوت رفتار می‌کنند؛ متد اشتباه بی‌صدا شبکهٔ ایمنی را خاموش می‌کند.

تعریف (RFC 9110): «A request method is considered "idempotent" if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. Of the request methods defined by this specification, PUT, DELETE, and safe request methods are idempotent.» POST به‌طور پیش‌فرض نه safe است نه idempotent.

متدSafeIdempotentکش‌پذیرکاربرد در این API
GETبلهبلهبلهخواندن سفارش، فهرست، poll وضعیت
HEADبلهبلهبلهبررسی وجود و ETag
PUTنهبلهنهجایگزینی کامل یک representation (مثلاً پروفایل مشتری)
DELETEنهبلهنهحذف یک پیش‌نویس
PATCHنهتضمین نشدهنهبه‌روزرسانی جزئی دادهٔ ساده، نه گذار وضعیت
POSTنهنهبه‌ندرتفرمان، ایجاد؛ با کلید idempotent کنید
Why idempotency matters: a retry after a timeout
1  client -> POST /orders/o1/cancellation-requests (Idempotency-Key: k1)
2  server    stores request can_1, answers 202 ... response lost on the network
3  client    times out, sends the same request again with Idempotency-Key: k1
4  server    finds key k1 -> returns can_1 again (no second request, no second refund)

سناریوی واقعی: کلاینت موبایل روی شبکهٔ ضعیف POST /payments را سه بار retry می‌کند. بدون کلید، سه شارژ. Stripe همین دفاع را مستند کرده: «When creating or updating an object, use an idempotency key. Then, if a connection error occurs, you can safely repeat the request without risk of creating a second object or performing the update twice.»

چه چیزی فراهم می‌کند: راهنمای Zalando هدر Idempotency-Key را در دستهٔ «MAY consider» می‌گذارد؛ Stripe آن را برای همهٔ POSTها استاندارد کرده. کد ما کلید را کنار درخواست ذخیره می‌کند (به سازوکار و برای بحث کلی API Idempotency). سمت مصرف‌کنندهٔ همین ایده در Idempotent Consumers & the Inbox Pattern است.

درخواست‌های شرطی: ETag، If-Match، 304، 412، 428 حیاتی ​

به زبان ساده: با هر خواندن یک برچسب نسخه به کلاینت بدهید. برای خواندن: «فقط اگر عوض شده بدنه را بفرست». برای فرمان: «فقط اگر نسخهٔ من هنوز به‌روز است انجام بده».

بدفهمی رایج: «optimistic locking قابلیت دیتابیس است، نه HTTP.» ستون version در aggregate دقیقاً همان چیزی است که ETag حمل می‌کند. HTTP برای دفاع در برابر lost update یک نام استاندارد می‌دهد.

تعریف: ETag یک validator برای representation است. If-None-Match روی GET revalidation ارزان می‌سازد (304 Not Modified). If-Match روی فرمان آن را شرطی می‌کند؛ اگر برچسب کهنه باشد پاسخ 412 Precondition Failed است. RFC 6585 کد 428 Precondition Required را برای سروری اضافه کرد که اصرار دارد: «Its typical use is to avoid the "lost update" problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server».

T1 (clerk A)                         T2 (clerk B)                     server version
1  GET /orders/o1 -> ETag W/"2"      GET /orders/o1 -> ETag W/"2"     2
2  POST .../lines (adds a mug)                                        2 -> 3
3                                    POST .../placement If-Match W/"2"
4                                    <- 412 Precondition Failed        3 (B re-reads, sees the mug)
5                                    GET -> W/"3"; POST ... If-Match W/"3" -> 200   3 -> 4
هدرجهتمعناانتخاب ما
ETag: W/"3"پاسخvalidator ضعیف = version aggregateروی هر representation سفارش
If-None-Matchدرخواست GETrevalidate304 بدون بدنه
If-Matchدرخواست فرمانفرمان شرطیروی add-line اختیاری، روی placement اجباری
Cache-Control: private, max-age=0, must-revalidateپاسخrevalidate اجباری، هرگز مشترکخواندن سفارش داده شخصی دارد

راه‌حل / نحوهٔ استفاده: برچسب را از version در repository بدهید؛ در application service به‌صورت expected بپذیرید؛ ErrVersionConflict را به 412 نگاشت کنید. در GraphQL هدر نیست: همین ایده فیلد ورودی expectedVersion می‌شود (به فرمان در GraphQL).

Problem Details (RFC 9457) حیاتی ​

به زبان ساده: هر خطا یک شکل دارد: یک URI به نام type، یک title کوتاه، status HTTP و detail و افزونه‌های اختیاری.

بدفهمی رایج: «type صفحه‌ای برای انسان است، هر رشته‌ای می‌شود.» type کلید ماشینی پایدار است. کلاینت روی آن شاخه می‌زند؛ مستندات می‌تواند پشتش باشد؛ title و detail آزادانه عوض می‌شوند.

تعریف: RFC 9457 «defines a "problem detail" to carry machine-readable details of errors in HTTP response content to avoid the need to define new error response formats for HTTP APIs.» نوع رسانه application/problem+json. اعضا: type، title، status، detail، instance و اعضای افزونه (ما errors[] با JSON Pointer اضافه می‌کنیم).

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
{ "type": "https://api.example.com/problems/validation-failed",
  "title": "Your request is invalid", "status": 422,
  "instance": "/orders",
  "errors": [ {"pointer": "/customerId", "detail": "is required"},
              {"pointer": "/currency",   "detail": "must be a 3-letter ISO 4217 code"} ] }
شکستStatusپسوند type (منتشرشده)منبع در دامنه
id ناشناخته404not-foundErrNotFound
ویرایش سفارش ثبت‌شده409order-not-editableErrNotDraft
ثبت بدون خط422order-emptyErrEmptyOrder
ورودی بد422validation-failedاعتبارسنجی درخواست
If-Match کهنه412stale-representationErrVersionConflict
If-Match غایب428precondition-requiredhandler
لغو سفارشِ لغوشده409order-not-cancellableErrAlreadyCancelled
هر چیز دیگر500about:blankلاگ می‌شود، هرگز نشت نمی‌کند

راه‌حل: یک تابع خطای دامنه را به problem نگاشت می‌کند (fromError در Go، ProblemDetails::fromFailure در PHP). متن خطای داخلی بیرون نمی‌رود مگر برای کلاینت نوشته شده باشد.

go
// Package rest publishes the Sales context over HTTP. It owns the wire shapes
// (DTOs); it never serialises the aggregate itself.
package rest

import (
	"encoding/json"
	"errors"
	"net/http"

	"academy/api-realization-rest-graphql/sales"
)

const problemBase = "https://api.example.com/problems/"

// Problem is an RFC 9457 problem details object with two extension members.
type Problem struct {
	Type     string       `json:"type"`
	Title    string       `json:"title"`
	Status   int          `json:"status"`
	Detail   string       `json:"detail,omitempty"`
	Instance string       `json:"instance,omitempty"`
	Errors   []FieldError `json:"errors,omitempty"` // extension: validation failures
}

// FieldError points at one invalid input member (JSON Pointer).
type FieldError struct {
	Pointer string `json:"pointer"`
	Detail  string `json:"detail"`
}

func writeProblem(w http.ResponseWriter, r *http.Request, p Problem) {
	p.Instance = r.URL.Path
	w.Header().Set("Content-Type", "application/problem+json")
	w.WriteHeader(p.Status)
	_ = json.NewEncoder(w).Encode(p)
}

// fromError maps a domain or application error to a stable problem type.
// The mapping is the single place where internal errors become public codes.
func fromError(err error) Problem {
	switch {
	case errors.Is(err, sales.ErrNotFound):
		return Problem{Type: problemBase + "not-found", Title: "Resource not found", Status: http.StatusNotFound}
	case errors.Is(err, sales.ErrVersionConflict):
		return Problem{Type: problemBase + "stale-representation", Title: "The order changed since you read it", Status: http.StatusPreconditionFailed,
			Detail: "Re-read the order and retry with the new ETag."}
	case errors.Is(err, sales.ErrNotDraft):
		return Problem{Type: problemBase + "order-not-editable", Title: "Order is not editable", Status: http.StatusConflict,
			Detail: "Only a draft order can be changed."}
	case errors.Is(err, sales.ErrEmptyOrder):
		return Problem{Type: problemBase + "order-empty", Title: "Order has no lines", Status: http.StatusUnprocessableEntity}
	case errors.Is(err, sales.ErrBadQuantity), errors.Is(err, sales.ErrUnknownProduct):
		return Problem{Type: problemBase + "validation-failed", Title: "Your request is invalid", Status: http.StatusUnprocessableEntity,
			Detail: err.Error()}
	case errors.Is(err, sales.ErrAlreadyCancelled), errors.Is(err, sales.ErrNotCancellable):
		return Problem{Type: problemBase + "order-not-cancellable", Title: "Order cannot be cancelled", Status: http.StatusConflict,
			Detail: err.Error()}
	}
	// Never leak internals: log err on the server, return a generic problem.
	return Problem{Type: "about:blank", Title: "Internal Server Error", Status: http.StatusInternalServerError}
}

نشان دادن سازگاری نهایی: 202، Location و منبع وضعیت حیاتی ​

به زبان ساده: اگر کار بعداً تمام می‌شود، بگویید: «پذیرفته شد، اینجا تماشا کنید».

بدفهمی رایج: «200 با وضعیت جدید برگردان؛ کلاینت لازم نیست بداند ناهمگام است.» آن‌وقت کلاینت «لغوشده» نشان می‌دهد برای سفارشی که Fulfilment هنوز آزادش نکرده، و به کاربر یک چیز گفته می‌شود در حالی که انبار چیز دیگری انجام می‌دهد.

تعریف (RFC 9110): «The 202 (Accepted) status code indicates that the request has been accepted for processing, but the processing has not been completed. ... The representation sent with this response ought to describe the request's current status and point to (or embed) a status monitor that can provide the user with an estimate of when the request will be fulfilled.» راهنمای Microsoft برای long-running operation همین را می‌گوید: «DO return status code 202-Accepted ... when a PUT, POST, or DELETE method completes asynchronously.»

ClientSales APIWorkerFulfilmentPOST /orders/o1/cancellation-requestsIdempotency-Key: k1202 Accepted, Location, Retry-After: 1state: pendingenqueuerelease stockreleasedcancel order, request completedGET /cancellation-requests/can_1200 pending (not yet)state change visibleGET /cancellation-requests/can_1200 completed, link to orderAlternative to polling: webhook sales.order.cancelled.v1 to the client's endpoint.
Timeline: cancelling a placed order (the saga is in /messaging/saga-pattern)
1  client   POST /orders/o1/cancellation-requests  {"reason":"late"}  Idempotency-Key: k1
2  api      INSERT cancellation_request(can_1, pending)  -- one local transaction
3  api   -> 202 Accepted  Location: /cancellation-requests/can_1  Retry-After: 1
4  worker   Fulfilment.ReleaseStock(o1)           -- may take seconds, may fail
5  worker   order.Cancel(); request.state = completed (or rejected + detail)
6  client   GET /cancellation-requests/can_1  ->  pending ... then completed + link to /orders/o1
راه خبر دادن به کلاینتمناسب برایهزینه
Poll کردن منبع وضعیتکلاینت ساده، انتظار کوتاهدرخواست هدررفته؛ به Retry-After احترام بگذارید
Webhook به URL کلاینتسرور به سرور، شرکاامضا، retry، لاگ تحویل (به Webhooks)
GraphQL subscription / SSEUIهای زندهاتصال بلندمدت که باید اداره شود
انتظار همگام تا N ثانیه، وگرنه 202عملیات بیشتر سریعدو مسیر کد

سناریوهای واقعی: بازپرداخت، بررسی KYC، تولید گزارش، encode ویدیو، انتقال بانکی، لغو چیزی که قبلاً picking شده.

راه‌حل: درخواست را به‌صورت یک رکورد (CancellationRequest) مدل کنید: به کلاینت چیزی برای GET می‌دهد، به worker چیزی برای idempotent کردن و به پشتیبانی چیزی برای خواندن.

Hypermedia و سطوح Richardson مهم ​

به زبان ساده: پاسخ سرور لینک کارهای بعدی را حمل می‌کند، پس کلاینت لینک را دنبال می‌کند به‌جای ساختن URL.

بدفهمی رایج: «اگر سطح 3 نباشد REST نیست.» فهرست قیدهای Fielding hypermedia را دارد، درست؛ اما بیشتر APIهای کسب‌وکاری هزینهٔ سطح 2 را می‌دهند و لینک را فقط جایی می‌افزایند که کمک می‌کند (کارهای وابسته به وضعیت، pagination، منابع مرتبط).

سطح (Fowler)ایدهمثال اینجا
0یک endpoint، تونل‌زنی (RPC روی HTTP)POST /api با نام عملیات
1منابع/orders/o1
2فعل‌ها و status codeهای HTTPPOST می‌سازد 201، تعارض 409، GET کش‌پذیر
3کنترل‌های hypermedia_links.placement فقط وقتی سفارش پیش‌نویس است

چه وقت لینک می‌ارزد: (الف) فرمان‌های بعدیِ مجاز به وضعیت بستگی دارند و سرور به کلاینت می‌گوید (placement برای پیش‌نویس، cancellation-requests برای سفارش ثبت‌شده)؛ (ب) pagination (next)؛ (پ) APIهای عمومی با کلاینت ناشناس زیاد؛ (ت) تکامل API، چون کلاینتی که href را دنبال می‌کند از جابه‌جایی URI جان سالم به‌در می‌برد.

چه وقت نمی‌ارزد: API خصوصی با یک کلاینت تولیدشده و طرح URL ثابت؛ گردش‌کار ثابتی که SDK آن را دارد.

قالبچه چیزی را استاندارد می‌کندچه وقت
JSON ساده + _links (این فصل)هیچ، قرارداد محلینیاز کوچک و صریح
HAL_links و _embeddedREST پر از لینک با ابزار
JSON:APIشیء منبع، رابطه، include، sparse fieldset، لینک‌های صفحهقرارداد آماده می‌خواهید و کلاینت‌هایی مثل Ember Data
Siren، Hydraaction و فرم در پاسخکلاینت‌های کاملاً hypermedia

JSON:API یک specification است (در زمان نگارش v1.1) با application/vnd.api+json؛ مستندات API Resource در Laravel 13 هم JSON:API resource را شرح می‌دهد، پس بدون بستهٔ اضافه در دسترس است.

Pagination، فیلتر و مرتب‌سازی مهم ​

به زبان ساده: هرگز «همهٔ سفارش‌ها» برنگردانید. یک صفحه و نشانگر صفحهٔ بعد بدهید.

بدفهمی رایج: «?page=7&per_page=20 کافی است.» offset وقتی داده بین دو درخواست عوض شود ردیف جا می‌اندازد یا تکرار می‌کند و با بزرگ شدن offset کند می‌شود (جزئیات در Pagination).

قرارداددرخواستپاسخیادداشت
Keyset cursor (ما)?limit=20&cursor=Mgitems، nextCursorمات، پایدار زیر insert
هدر LinkهمانLink: <...>; rel="next"RFC 8288؛ برای کلاینت عمومی خوب
Offset?offset=40&limit=20items، totalفقط فهرست کوچک و کم‌تغییر
GraphQL connectionfirst، afteredges { cursor node }، pageInfoبه pagination در GraphQL
پارامترقاعده
فیلترهابا زبان فراگیر نام‌گذاری شوند: status=placed، customerId=...؛ فیلتر ناشناس 400 است نه نادیده
Sortsort=-placedAt,id با whitelist مستند و tiebreaker یکتا تا cursor پایدار باشد
حدهاپیش‌فرض و سقف سخت در قرارداد (limit 20، حداکثر 100)
Cursorبرای کلاینت مات؛ قالبش بدون نسخهٔ جدید عوض می‌شود
Tenantسرور از token اعمال می‌کند، هرگز از query string
sql
-- The query behind GET /orders?status=placed&limit=20&cursor=...
SELECT id, customer_id, status, placed_at, seq
FROM orders
WHERE customer_id = $1          -- from the token, not from the client
  AND status = 'placed'
  AND seq > $2                  -- decoded cursor
ORDER BY seq                    -- unique, indexed (customer_id, seq)
LIMIT 21;                       -- one extra row tells us whether a next page exists

نسخه‌بندی زبان منتشرشده مهم ​

به زبان ساده: API را طوری عوض کنید که کلاینت‌های قدیمی کار کنند؛ وقتی نشد، قدیم و جدید را کنار هم اجرا کنید و تاریخ پایان را اعلام کنید.

بدفهمی رایج: «/v2/ را در URL بگذار و تمام.» نسخه در URL یک برچسب است؛ کار سخت تصمیم‌گیری است که کدام تغییرها افزایشی و کدام شکننده‌اند و اجرای هر دو به‌اندازهٔ کافی.

تغییرشکننده؟قاعده
فیلد اختیاری جدید در پاسخنهکلاینت باید فیلد ناشناس را نادیده بگیرد (tolerant reader)
فیلد اختیاری جدید در درخواستنهپیش‌فرض رفتار قدیمی
endpoint یا فرمان جدیدنهقدیمی‌ها می‌مانند
مقدار enum جدید در پاسخبرای کلاینت سخت‌گیر بلهمستند کنید enum باز است؛ یا فیلد جدید اضافه کنید
حذف یا تغییر نام فیلدبلهنسخهٔ جدید، یا اول نام جدید را اضافه کنید و قدیمی را نگه دارید
سخت‌تر کردن validationبلهنسخهٔ جدید
تغییر معنای فیلدبلههرگز نامی را برای معنای جدید دوباره به‌کار نبرید
فیلد اجباری جدید در درخواستبلهنسخهٔ جدید
سبکمثالمزیتعیب
URI/v2/ordersدیده می‌شود، مسیریابی در gateway آساننسخه جزو هر لینک است
HeaderSales-Version: 2026-11-01URI تمیز، نسخهٔ تاریخیپنهان؛ امتحان در مرورگر سخت‌تر
Media typeAccept: application/vnd.sales.order.v2+jsonنسخه برای هر representationپیچیدگی ابزار و کش
هیچ (GraphQL)تغییر افزایشی به‌علاوهٔ @deprecatedیک گرافانضباط و تحلیل مصرف لازم است

چرخهٔ عمر deprecation دو هدر دارد: Deprecation (API دیگر توصیه نمی‌شود) و Sunset در RFC 8594 که «indicates that a URI is likely to become unresponsive at a specified point in the future». خود RFC دو مرحله را جدا می‌کند: اول deprecation، بعد decommission. بحث کامل در API Versioning؛ زاویهٔ DDD این است که زبان منتشرشده نسخه‌بندی می‌شود، نه aggregate.

Timeline: retiring Order.v1 "customerId as int"
1  month 0   publish v2 (customerId: string); v1 still served; add Deprecation header to v1
2  month 1   gateway analytics: 12 consumers still on v1; email each owner (keys identify them)
3  month 4   add Sunset: Thu, 01 Jul 2027 00:00:00 GMT to every v1 response
4  month 7   v1 returns 410 Gone with a problem pointing to the migration guide

قرارداد-اول با OpenAPI حیاتی ​

به زبان ساده: اول توصیف API را بنویسید، با مصرف‌کننده‌ها بازبینی کنید، بعد کد را مطابقش بسازید و بگذارید ماشین تطابق را بررسی کند.

بدفهمی رایج: «فایل OpenAPI را آخر کار از روی کد تولید می‌کنیم.» مستند تولیدشده می‌گوید کد چه می‌کند، با باگ‌هایش. قراردادی که اول نوشته می‌شود می‌گوید API چه قولی می‌دهد؛ کد بعد به آن ملزم می‌شود.

تعریف: OpenAPI Specification 3.1.0 (15 فوریهٔ 2021) یک API روی HTTP را در YAML یا JSON توصیف می‌کند: path، operation، پارامتر، بدنهٔ درخواست، پاسخ، security scheme و componentهای قابل‌استفادهٔ مجدد، با JSON Schema برای داده. قاعدهٔ Zalando همان است که باید کپی کنید: «Microservices development begins with API specification outside the code and ideally involves ample peer-review feedback to achieve high-quality APIs.»

گامچه می‌شودابزار
1 طراحیsales.openapi.yaml از زبان منتشرشده نوشته می‌شودویرایشگر، Stoplight، Swagger Editor
2 Lintقواعد سبک و سیاست build را رد می‌کنندSpectral با ruleset تیم
3 بازبینیمصرف‌کننده‌ها و تیم پلتفرم روی diff نظر می‌دهندPull request
4 بررسی شکستنمقایسه با قرارداد منتشرشده؛ تغییر شکننده fail می‌شودoasdiff، openapi-diff
5 تولیدکلاینت و stub/type سرور از فایلopenapi-generator، oapi-codegen (Go)، بسته‌های Laravel
6 راستی‌آزماییسرور واقعی در برابر قرارداد اجرا می‌شودSchemathesis، Dredd، Prism (mock)
7 انتشارمستندات روی پورتال توسعه‌دهندهRedoc، Swagger UI
yaml
# The core of the contract for the cancellation command (full file below).
/orders/{orderId}/cancellation-requests:
  post:
    operationId: requestOrderCancellation
    security: [{ oauth2: ["orders:write"] }]
    parameters:
      - { name: Idempotency-Key, in: header, schema: { type: string, maxLength: 64 } }
    responses:
      '202':
        description: Accepted; poll the Location resource
        headers: { Location: { schema: { type: string } }, Retry-After: { schema: { type: integer } } }
      '409': { $ref: '#/components/responses/Problem' }
yaml
openapi: 3.1.0
info:
  title: Sales API
  version: 1.4.0
  summary: The published language of the Sales context, over HTTP.
  description: >
    Open Host Service of the Sales bounded context. Resources follow the
    ubiquitous language (order, line, placement, cancellation request).
  contact: { name: Sales team, email: sales-api@example.com }
servers:
  - url: https://api.example.com
security:
  - oauth2: ["orders:read"]
tags:
  - name: Orders
  - name: Cancellation
paths:
  /orders:
    post:
      operationId: createDraftOrder
      tags: [Orders]
      summary: Start a draft order
      security: [{ oauth2: ["orders:write"] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateOrder' }
      responses:
        '201':
          description: Draft created
          headers:
            Location: { schema: { type: string, format: uri-reference } }
            ETag: { $ref: '#/components/headers/ETag' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '422': { $ref: '#/components/responses/Problem' }
    get:
      operationId: listOrders
      tags: [Orders]
      summary: List my orders (keyset pagination)
      parameters:
        - { name: status, in: query, schema: { $ref: '#/components/schemas/OrderStatus' } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }
        - { name: cursor, in: query, description: "Opaque; copy nextCursor from the previous page.", schema: { type: string } }
      responses:
        '200':
          description: One page of orders
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OrderPage' }
  /orders/{orderId}:
    parameters:
      - { name: orderId, in: path, required: true, schema: { type: string } }
    get:
      operationId: getOrder
      tags: [Orders]
      summary: Read one order
      parameters:
        - { name: If-None-Match, in: header, schema: { type: string } }
      responses:
        '200':
          description: The order
          headers:
            ETag: { $ref: '#/components/headers/ETag' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '304': { description: Not modified }
        '404': { $ref: '#/components/responses/Problem' }
  /orders/{orderId}/lines:
    parameters:
      - { name: orderId, in: path, required: true, schema: { type: string } }
    post:
      operationId: addOrderLine
      tags: [Orders]
      summary: Add a line (price is taken from Catalog)
      security: [{ oauth2: ["orders:write"] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/AddLine' }
      responses:
        '201':
          description: Line added; the updated order is returned
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '409': { $ref: '#/components/responses/Problem' }
        '422': { $ref: '#/components/responses/Problem' }
  /orders/{orderId}/placement:
    parameters:
      - { name: orderId, in: path, required: true, schema: { type: string } }
    post:
      operationId: placeOrder
      tags: [Orders]
      summary: Place the order (a command, named as the business names it)
      security: [{ oauth2: ["orders:write"] }]
      parameters:
        - { name: If-Match, in: header, required: true, schema: { type: string }, example: 'W/"2"' }
      responses:
        '200':
          description: Placed
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '412': { $ref: '#/components/responses/Problem' }
        '422': { $ref: '#/components/responses/Problem' }
        '428': { $ref: '#/components/responses/Problem' }
  /orders/{orderId}/cancellation-requests:
    parameters:
      - { name: orderId, in: path, required: true, schema: { type: string } }
    post:
      operationId: requestOrderCancellation
      tags: [Cancellation]
      summary: Ask to cancel (accepted now, decided later)
      security: [{ oauth2: ["orders:write"] }]
      parameters:
        - { name: Idempotency-Key, in: header, schema: { type: string, maxLength: 64 } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason]
              properties: { reason: { type: string, maxLength: 500 } }
      responses:
        '202':
          description: Accepted; poll the Location resource
          headers:
            Location: { schema: { type: string, format: uri-reference } }
            Retry-After: { schema: { type: integer } }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CancellationRequest' }
        '409': { $ref: '#/components/responses/Problem' }
  /cancellation-requests/{requestId}:
    get:
      operationId: getCancellationRequest
      tags: [Cancellation]
      summary: Status of a cancellation request
      parameters:
        - { name: requestId, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: Current state
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CancellationRequest' }
        '404': { $ref: '#/components/responses/Problem' }
components:
  securitySchemes:
    oauth2:
      type: oauth2
      flows:
        clientCredentials:
          tokenUrl: https://id.example.com/oauth/token
          scopes:
            orders:read: Read orders
            orders:write: Place and cancel orders
  headers:
    ETag:
      description: Weak validator; send it back as If-Match on commands.
      schema: { type: string }
  responses:
    Problem:
      description: RFC 9457 problem details
      content:
        application/problem+json:
          schema: { $ref: '#/components/schemas/Problem' }
  schemas:
    OrderStatus: { type: string, enum: [draft, placed, cancelled] }
    Money:
      type: object
      required: [amountMinor, currency]
      properties:
        amountMinor: { type: integer, format: int64 }
        currency: { type: string, pattern: '^[A-Z]{3}$' }
    CreateOrder:
      type: object
      required: [customerId, currency]
      additionalProperties: false
      properties:
        customerId: { type: string }
        currency: { type: string, pattern: '^[A-Z]{3}$' }
    AddLine:
      type: object
      required: [sku, quantity]
      additionalProperties: false
      properties:
        sku: { type: string }
        quantity: { type: integer, minimum: 1, maximum: 50 }
    Line:
      type: object
      required: [sku, quantity, unitPrice]
      properties:
        sku: { type: string }
        quantity: { type: integer }
        unitPrice: { $ref: '#/components/schemas/Money' }
    Link:
      type: object
      required: [href]
      properties:
        href: { type: string }
        method: { type: string }
    Order:
      type: object
      required: [id, customerId, status, lines, total, _links]
      properties:
        id: { type: string }
        customerId: { type: string }
        status: { $ref: '#/components/schemas/OrderStatus' }
        lines: { type: array, items: { $ref: '#/components/schemas/Line' } }
        total: { $ref: '#/components/schemas/Money' }
        placedAt: { type: [string, 'null'], format: date-time }
        _links: { type: object, additionalProperties: { $ref: '#/components/schemas/Link' } }
    OrderPage:
      type: object
      required: [items]
      properties:
        items: { type: array, items: { $ref: '#/components/schemas/Order' } }
        nextCursor: { type: string }
    CancellationRequest:
      type: object
      required: [id, orderId, state, reason]
      properties:
        id: { type: string }
        orderId: { type: string }
        state: { type: string, enum: [pending, completed, rejected] }
        reason: { type: string }
        detail: { type: string }
        _links: { type: object, additionalProperties: { $ref: '#/components/schemas/Link' } }
    Problem:
      type: object
      required: [type, title, status]
      properties:
        type: { type: string, format: uri }
        title: { type: string }
        status: { type: integer }
        detail: { type: string }
        instance: { type: string }
        errors:
          type: array
          items:
            type: object
            required: [pointer, detail]
            properties: { pointer: { type: string }, detail: { type: string } }

ruleset تیم سیاست را به build شکست‌خورده تبدیل می‌کند: هر 4xx و 5xx باید به پاسخ Problem ارجاع دهد، هر POST باید scope خودش را بنویسد و path نباید فعل داشته باشد.

yaml
# Team ruleset: extends the built-in OpenAPI rules and adds our conventions.
extends: ["spectral:oas"]
rules:
  sales-problem-on-errors:
    description: 4xx and 5xx responses must be RFC 9457 problem details.
    severity: error
    given: "$.paths[*][*].responses[?(@property.match(/^[45]/))]"
    then: { field: "$ref", function: pattern, functionOptions: { match: "#/components/responses/Problem$" } }
  sales-no-verbs-in-paths:
    description: Paths name resources, not verbs (task nouns such as /placement are fine).
    severity: warn
    given: "$.paths[*]~"
    then: { function: pattern, functionOptions: { notMatch: "/(get|set|create|update|delete)[A-Z-]" } }
  sales-commands-need-security:
    description: Every POST must name its scope.
    severity: error
    given: "$.paths[*].post"
    then: { field: security, function: truthy }

Design-first در برابر code-first: برای Open Host Service طراحی-اول مناسب است، چون قرارداد یک قول است؛ code-first برای APIهای داخلی با یک مصرف‌کننده پذیرفتنی است به شرط اینکه فایل تولیدشده باز هم در بازبینی diff شود. ترکیب غلط این است که فایل را بعد از واقعه بنویسید و هرگز روی سرور اجرایش نکنید.

API management مهم ​

به زبان ساده: gateway و پورتالی دور API شما: چه کسی اجازهٔ فراخوانی دارد، چقدر، چه کسی صدا زد و چطور ثبت‌نام می‌کند.

بدفهمی رایج: «API gateway جای قواعد کسب‌وکار است.» gateway سیاست‌های عرضی را اجرا می‌کند؛ قواعدی که Sales را تعریف می‌کنند در Sales می‌مانند. Kong gatewayش را «a reverse proxy that lets you manage, configure, and route requests to your APIs» توصیف می‌کند.

قابلیتچه می‌کندمحصولات
احراز هویتکلید API، اعتبارسنجی token در OAuth 2.0 / OIDC، mTLSpluginهای Kong، policyهای Apigee، authorizerهای AWS API Gateway
سهمیه و rate limitبرای هر کلید، هر پلن، هر routeKong Rate Limiting، Apigee Quota، RateLimiter در Laravel
مسیریابی و تبدیلمسیریابی بر پایهٔ path و نسخه، بازنویسی هدرrouteهای Kong، proxyهای Apigee، Envoy
تحلیلچه کسی چه صدا می‌زند، نرخ خطا، تأخیرKong Konnect، Apigee Analytics
پورتال توسعه‌دهندهمستندات، ثبت‌نام، صدور کلیدKong Dev Portal، پورتال Apigee
Monetisationپلن، صورت‌حساب به ازای فراخوانیmonetisation در Apigee، سهمیهٔ پلنی
چرخهٔ عمراعلان deprecation، بازنشستگی نسخهپورتال به‌علاوهٔ analytics

gateway نسبت به context کجاست. جلوی آن. context مالک قرارداد (OpenAPI) و قواعد است؛ gateway سیاست را از قرارداد اجرا می‌کند (scope، سهمیه) و به هر مصرف‌کننده هویت می‌دهد. برنامه باز هم برای هر منبع مجوز می‌دهد، چون gateway نمی‌داند سفارش o1 مال مشتری c1 است. الگوهای لبه، BFF و mesh: API Gateway, BFF & Service Mesh.

کجادرستغلط
Gatewayبررسی کلید، scope درشت، سهمیه، TLS، حد اندازهٔ درخواست، مسیریابی نسخهمحاسبهٔ جمع، گذار وضعیت
Contextبررسی مالکیت، invariantها، idempotency، معنای خطامنطق صورت‌حساب هر پلن
هر دوrate limit (درشت در لبه، ریز در برنامه، مثل RateLimiting.php)فقط یک لایه
Timeline: one call through the stack
1  client   POST /orders/o1/placement  Authorization: Bearer <token>
2  gateway  verify token, check scope orders:write, check plan quota, add X-Consumer-Id
3  gateway  route /v1/orders/* to the Sales upstream
4  sales    authenticate, authorise per resource (order belongs to this customer?)
5  sales    If-Match check, Service.Place, map result to JSON or problem+json
6  gateway  log status and latency per consumer, emit metrics

GraphQL: schema همان زبان منتشرشده است حیاتی ​

به زبان ساده: schema در GraphQL منوی تایپ‌دار هر چیزی است که کلاینت می‌تواند بخواهد؛ کلاینت فیلدهای دلخواهش را انتخاب می‌کند.

بدفهمی رایج: «schema را از دیتابیس تولید کن و تمام.» schemaای که آینهٔ جدول‌هاست همان عیب json.Marshal(row) را دارد: ذخیره‌سازی را منتشر می‌کند. راهنمای خود GraphQL می‌گوید «Model your business domain as a graph» و «Design and evolve a type system over time without versions» و یادآوری می‌کند spec دربارهٔ شبکه، مجوز و pagination «is intentionally silent» است؛ یعنی اینها کار طراحی‌اند.

تعریف: schema (SDL) typeها، fieldها، enumها، input typeها و rootهای Query، Mutation و (اختیاری) Subscription را تعریف می‌کند. هر field یک resolver دارد. ویرایش October 2021 می‌گوید selection set سطح بالای mutation «should be executed serially»؛ fieldهای query می‌توانند موازی اجرا شوند.

قاعدهچرادر schema ما
typeها از مدل منتشرشده می‌آیندschema از تغییر ذخیره‌سازی جان سالم به‌در می‌بردOrder، OrderLine، Money نه orders_row
Value object تبدیل به type می‌شودپول {amountMinor, currency} است، نه floattype Money
وضعیت = enumکلاینت نمی‌تواند وضعیت اختراع کندOrderStatus، CancellationState
دادهٔ context دیگر typeای است که همان context داردCatalog مالک Product استOrderLine.product با loader
nullable به‌قصدnon-null جایی که قرارداد تضمین می‌کند، nullable جایی که نبودن عادی استplacedAt: DateTime
رشتهٔ مستنداتschema همان مستند است"""...""" روی هر type
Deprecate کنید، حذف نهتکامل بدون نسخه@deprecated(reason: "...")

SDL کامل (نسخهٔ gqlgen؛ نسخهٔ Lighthouse همان typeها را با directive دارد):

graphql
"""An ISO 8601 date-time such as 2026-11-25T09:30:00Z."""
scalar DateTime

"""Money in minor units (cents) plus the ISO 4217 currency."""
type Money {
  amountMinor: Int!
  currency: String!
}

enum OrderStatus {
  DRAFT
  PLACED
  CANCELLED
}

enum CancellationState {
  PENDING
  COMPLETED
  REJECTED
}

"""Catalog's product, resolved through a batched loader."""
type Product {
  sku: ID!
  name: String!
}

type OrderLine {
  sku: ID!
  quantity: Int!
  unitPrice: Money!
  product: Product!
}

type Order {
  id: ID!
  customerId: ID!
  status: OrderStatus!
  lines: [OrderLine!]!
  total: Money!
  placedAt: DateTime
  """Bumped on every change; pass it back as expectedVersion."""
  version: Int!
}

type OrderEdge {
  cursor: String!
  node: Order!
}

type PageInfo {
  hasNextPage: Boolean!
  endCursor: String
}

type OrderConnection {
  edges: [OrderEdge!]!
  pageInfo: PageInfo!
}

type CancellationRequest {
  id: ID!
  orderId: ID!
  state: CancellationState!
  reason: String!
  detail: String
}

"""A business problem the client can show; not a transport error."""
type UserError {
  code: String!
  message: String!
  field: String
}

type Query {
  order(id: ID!): Order
  orders(customerId: ID!, status: OrderStatus, first: Int = 20, after: String): OrderConnection!
  cancellationRequest(id: ID!): CancellationRequest
}

input CreateDraftOrderInput {
  customerId: ID!
  currency: String!
}

input AddOrderLineInput {
  orderId: ID!
  sku: ID!
  quantity: Int!
  expectedVersion: Int
}

input PlaceOrderInput {
  orderId: ID!
  expectedVersion: Int!
}

input RequestOrderCancellationInput {
  orderId: ID!
  reason: String!
  """Replay-safe: the same key returns the same request."""
  idempotencyKey: String
}

type CreateDraftOrderPayload {
  order: Order
  userErrors: [UserError!]!
}

type AddOrderLinePayload {
  order: Order
  userErrors: [UserError!]!
}

type PlaceOrderPayload {
  order: Order
  userErrors: [UserError!]!
}

type RequestOrderCancellationPayload {
  request: CancellationRequest
  userErrors: [UserError!]!
}

type Mutation {
  createDraftOrder(input: CreateDraftOrderInput!): CreateDraftOrderPayload!
  addOrderLine(input: AddOrderLineInput!): AddOrderLinePayload!
  placeOrder(input: PlaceOrderInput!): PlaceOrderPayload!
  requestOrderCancellation(input: RequestOrderCancellationInput!): RequestOrderCancellationPayload!
}

سناریوی واقعی: صفحهٔ سفارش وب خط‌ها را با نام محصول می‌خواهد؛ فهرست موبایل id، status و total؛ پشتیبانی Billing فقط مشتری و total. هر سه queryهای متفاوتی به یک schema می‌فرستند و سرور تغییری نمی‌کند.

فرمان، input type، payload و خطا در GraphQL حیاتی ​

به زبان ساده: mutation یک فرمان است. یک شیء ورودی می‌گیرد و payloadی برمی‌گرداند که یا نتیجه دارد یا فهرست مشکلات کسب‌وکاری.

بدفهمی رایج: «خطاها در آرایهٔ errors سطح بالا می‌روند.» آن آرایه برای شکست خودِ درخواست است (syntax، validation، crash). قاعده‌ای مثل «سفارش قبلاً ثبت شده» نتیجهٔ عادی است که UI باید نشانش بدهد؛ در payload به‌صورت userErrors مدلش کنید.

قاعدهٔ طراحیدلیل
mutation را با فرمان نام بگذارید: placeOrder، requestOrderCancellationهمان واژگان وظیفه‌محور REST
یک آرگومان input از نوع input typeتکامل‌پذیر: فیلد اختیاری اضافه شود، چیزی نمی‌شکند
payload برگردانید (PlaceOrderPayload)جا برای order، userErrors و بعداً بیشتر
شکست‌های کسب‌وکاری در userErrors { code message field }code کلید ماشینی است، مثل type در Problem
شکست‌های غیرمنتظره = خطای GraphQLباگ یا قطعی‌اند، نه نتیجه
توکن همزمانی به‌صورت ورودی: expectedVersionGraphQL هدر If-Match ندارد؛ ایده همان است
idempotency به‌صورت ورودی: idempotencyKeyقرارداد هدر Idempotency-Key وجود ندارد
null برای node غایب در queryorder(id) مقدار null می‌دهد نه خطا
Timeline: placeOrder with a stale version
1  client  mutation { placeOrder(input:{orderId:"o1", expectedVersion:1}) { order{id} userErrors{code} } }
2  server  Service.Place -> ErrVersionConflict (the order is at version 2)
3  server  HTTP 200  {"data":{"placeOrder":{"order":null,"userErrors":[{"code":"STALE_VERSION"}]}}}
4  client  re-reads the order, shows "the order changed", retries with version 2

راه‌حل: یک نگاشت‌گر کوچک userError(err) کنار resolverها (Go) یا در Presenter (PHP) که خطای دامنه را به کد تبدیل می‌کند و خطای ناشناخته را عبور می‌دهد. فهرست problemهای REST و کدهای خطای GraphQL باید همان شکست‌های کسب‌وکاری را با املای متفاوت بشمارند (order-not-editable و ORDER_NOT_EDITABLE).

Pagination با Relay connection مهم ​

به زبان ساده: fieldی که فهرست می‌دهد edges (هرکدام با cursor و node) و pageInfo برمی‌گرداند و کلاینت first: 20, after: "cursor" می‌خواهد.

بدفهمی رایج: «connection زیادی پیچیده است؛ یک list برگردان.» list ساده cursor حمل نمی‌کند و اضافه کردن pageInfo بعداً همهٔ کلاینت‌ها را می‌شکند. راهنمای pagination در GraphQL می‌گوید cursor-based «is the most powerful of those designed» چون offset یا id هم «can be implemented using cursor-based pagination»، و cursor مات را توصیه می‌کند: «we suggest base64 encoding them».

قطعهمعنامنبع
first، afterبه جلو ببُر: N تای اول بعد از این cursorCursor Connections Specification
edges { cursor node }cursor مال edge است نه nodeهمان
pageInfo { hasNextPage endCursor }به کلاینت می‌گوید کجا بایستدهمان
Cursor ماتقالبش می‌تواند عوض شودهمان

resolver ما limit + 1 ردیف می‌گیرد تا hasNextPage را حساب کند و شمارهٔ ترتیب را به‌عنوان cursor کد می‌کند؛ همان query کلیدی هم به REST خدمت می‌کند هم GraphQL.

N+1 و dataloader حیاتی ​

به زبان ساده: وقتی 20 سفارش هرکدام محصولاتشان را می‌خواهند، سرور ساده 20 بار Catalog را صدا می‌زند. dataloader صبر می‌کند هر 20 نفر بخواهند، بعد یک بار صدا می‌زند.

بدفهمی رایج: «N+1 مشکل دیتابیس است.» روی هر مرزی رخ می‌دهد: SQL، HTTP به Catalog، کش. در سیستم توزیع‌شده هر فراخوانی اضافه یک شکست شبکه‌ای بالقوه هم هست.

تعریف: مستندات gqlgen: «Dataloaders consolidate the retrieval of information into fewer, batched calls.» مستندات Lighthouse همین تله را شرح می‌دهد: «Following a naive execution strategy, Lighthouse would first query a list of posts, then loop over that list and resolve the individual fields. The associated author for each post would be lazily loaded, querying the database once per post.»

Without a loader                                With a loader (one request)
1  orders(first:3) -> 3 orders, 6 lines         1  orders(first:3) -> 3 orders, 6 lines
2  line1.product -> Catalog.Products([A])       2  line1..6 product -> loader.Load(sku) x 6   (queued)
3  line2.product -> Catalog.Products([B])       3  after ~2 ms or when the level ends:
4  ... six calls, serial                        4  Catalog.Products([A,B]) once -> results fanned out
پشتهسازوکاردامنهٔ هر درخواست
Go با gqlgendataloadgen.Loader ساخته‌شده در middleware، WithWait(2ms)middleware یک Loaders تازه در context می‌گذارد
Laravel Lighthouse (رابطه‌های Eloquent)@belongsTo، @hasMany، @with queryهای رابطه را دسته می‌کنندداخلی
Laravel Lighthouse (دادهٔ خارجی)BatchLoaderRegistry::instance($info->path, ...) با برگرداندن GraphQL\Deferredیک نمونه برای هر مسیر query در درخواست

سه قاعده: (1) loader برای هر درخواست ساخته می‌شود، هرگز سراسری، وگرنه کشش بین کاربران نشت می‌کند؛ (2) تابع batch نتایج را به ترتیب کلیدها و با یک مدخل برای هر کلید برمی‌گرداند؛ (3) کلید غایب placeholder یا خطا برای همان کلید می‌دهد، نه برای کل batch. تست Go تأیید می‌کند «شش field محصول یک فراخوانی Catalog هزینه دارد».

go
package graph

import (
	"context"
	"net/http"
	"time"

	"github.com/vikstrous/dataloadgen"

	"academy/api-realization-rest-graphql/graph/model"
	"academy/api-realization-rest-graphql/sales"
)

type loadersKey struct{}

// Loaders holds one batching loader per request. A loader must never be
// shared across requests: its cache would leak data between callers.
type Loaders struct {
	Product *dataloadgen.Loader[string, *model.Product]
}

// NewLoaders builds the per-request loaders. All Product lookups requested
// within the wait window become one Catalog.Products call.
func NewLoaders(cat sales.Catalog) *Loaders {
	fetch := func(ctx context.Context, skus []string) ([]*model.Product, []error) {
		keys := make([]sales.SKU, len(skus))
		for i, s := range skus {
			keys[i] = sales.SKU(s)
		}
		found, err := cat.Products(ctx, keys)
		out := make([]*model.Product, len(skus))
		errs := make([]error, len(skus))
		for i, s := range skus {
			switch p, ok := found[sales.SKU(s)]; {
			case err != nil:
				errs[i] = err
			case ok:
				out[i] = &model.Product{Sku: s, Name: p.Name}
			default:
				// Unknown SKU: return a placeholder rather than failing the whole order.
				out[i] = &model.Product{Sku: s, Name: "(unavailable)"}
			}
		}
		return out, errs
	}
	return &Loaders{Product: dataloadgen.NewLoader(fetch, dataloadgen.WithWait(2*time.Millisecond))}
}

// Middleware attaches fresh loaders to every incoming request.
func Middleware(cat sales.Catalog, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := context.WithValue(r.Context(), loadersKey{}, NewLoaders(cat))
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

// For returns the loaders of the current request.
func For(ctx context.Context) *Loaders { return ctx.Value(loadersKey{}).(*Loaders) }

Federation، stitching و BFF مهم ​

به زبان ساده: هر context مالک بخش خودش از گراف است؛ چیزی بالاتر یک گراف را به کلاینت‌ها نشان می‌دهد.

بدفهمی رایج: «یک سرور GraphQL برای کل شرکت هدف است.» سرور گرافِ بی‌صاحب دیتابیس مشترک جدید می‌شود. مالکیت پیش context می‌ماند؛ ترکیب کار router یا BFF است.

رویکردایدهمناسب برای
Schema stitchinggateway schemaهای راه‌دور را با لینک دستی ادغام می‌کندکم‌تعداد؛ چسب را خودتان دارید
Apollo Federationsubgraphها entity و key اعلام می‌کنند؛ router یک supergraph می‌سازدتیم‌های زیاد که هرکدام typeهای خود را دارند. Apollo: «When combining multiple GraphQL APIs, the single, federated graph is called a supergraph.»
Backend for Frontend (BFF)برای هر نوع کلاینت یک API، در مالکیت تیم همان کلاینت، که APIهای contextها را صدا می‌زندوب و موبایل تجمیع متفاوت می‌خواهند؛ GraphQL را بیرون contextها نگه می‌دارد
Schemaی مستقل هر contextهر context GraphQL خودش را دارد؛ کلاینت چند تا را صدا می‌زندکلاینت کم، نیاز ساده

نگاشت به DDD: هر subgraph یک Open Host Service برای یک context است (Sales مالک Order، Catalog مالک Product، Identity مالک Customer)؛ کلید entity در federation (@key(fields: "sku") در directive اپولو) اجازه می‌دهد OrderLine.product در Sales به Product در Catalog اشاره کند بدون اینکه Sales مدل Catalog را import کند. BFF مصرف‌کننده است و می‌تواند یک anticorruption layer باشد. جزئیات router و BFF در API Gateway, BFF & Service Mesh.

gRPC، webhook و AsyncAPI تکمیلی ​

به زبان ساده: همان زبان منتشرشده می‌تواند یک سرویس protobuf، یک webhook یا یک جریان رویداد هم باشد.

پیاده‌سازیمناسب برایقالب قرارداداشاره
gRPCفراخوانی سرویس به سرویس با نوع سخت، streaming، تأخیر کم.protogRPC & Protobuf
Webhookخبر دادن به سیستم بیرونی که اتفاقی افتادJSON Schema + طرح امضاپایین
پیام / رویدادیکپارچگی ناهمگام، fan-outAsyncAPI، JSON Schema، Avro/ProtobufDomain Events vs Integration Events، Outbox Pattern
Server-Sent Events / GraphQL subscriptionUIهای زندهSDL / جریان رویدادGraphQL

webhook رویدادی است که روی HTTP push می‌شود. قواعد: بدنه را امضا کنید (HMAC با راز مشترک، با timestamp)، با backoff دوباره بفرستید و به هر تحویل id بدهید، گیرنده زود با 2xx تأیید کند و بعداً پردازش کند، لاگ تحویل برای مصرف‌کننده نگه دارید و schema رویداد را مثل هر بخش دیگر زبان منتشر کنید. AsyncAPI معادل OpenAPI برای APIهای رویدادمحور است: سندی که کانال، پیام و schema را توصیف می‌کند (صفحهٔ concepts در AsyncAPI). راه مطمئن فرستادن webhook از Sales outbox است: رویداد sales.order.cancelled.v1 را در همان تراکنش لغو بنویسید و یک relay تحویلش دهد (Outbox Pattern، Designing for Failure & Reliable Messaging).

امنیت لبهٔ API حیاتی ​

به زبان ساده: بدانید چه کسی صدا می‌زند، چه کاری مجاز است و به دادهٔ چه کسی دسترسی دارد، و هر سه را سمت سرور اعمال کنید.

بدفهمی رایج: «gateway token را بررسی می‌کند، پس سرویس لازم نیست چیزی بررسی کند.» token معتبر ثابت می‌کند چه کسی، نه کدام سفارش. بدون بررسی روی هر منبع، هر مشتری احرازشده با عوض کردن id می‌تواند هر سفارشی را بخواند (broken object-level authorization).

پرسشسازوکارمثال
چه کسی صدا می‌زند؟access token در OAuth 2.0 / OIDC، token در Sanctum، mTLS برای سرویس به سرویسauth:sanctum
چه کاری مجاز است؟Scope / ability روی tokenabilities:orders:write؛ Sanctum: tokenها «may be granted abilities / scopes which specify which actions the tokens are allowed to perform»
دادهٔ چه کسی؟بررسی مالکیت یا tenant روی هر منبعowned() در controller برای سفارش دیگران 404 می‌دهد
چقدر؟Rate limit برای هر token و هر routeRateLimiter::for('api', ...)، throttle:api، @throttle در Lighthouse
چه شکلی؟حد اندازهٔ بدنه، JSON سخت‌گیر (DisallowUnknownFields)، حداکثر عمق/پیچیدگی query در GraphQLhttp.MaxBytesReader، حدهای عمق/پیچیدگی در Lighthouse

قاعده‌هایی که حادثهٔ واقعی را جلو می‌گیرند:

  1. tenant از token، نه از درخواست. GET /orders?customerId=c9 نباید به c1 اجازهٔ خواندن سفارش‌های c9 بدهد؛ فهرست Laravel هر مشتری ارسالی کلاینت را نادیده می‌گیرد و createDraftOrder در GraphQL مشتری را از token می‌گیرد.
  2. برای منبع دیگران 404 نه 403، مگر وجودش عمومی باشد.
  3. Scope برای هر فرمان، نه برای خانوادهٔ endpoint: orders:read و orders:write.
  4. GraphQL یک endpoint دارد، پس مجوز به fieldها و resolverها می‌رود. @guard در Lighthouse خودش «does not log in users»: middleware AttemptAuthentication را اضافه کنید، بعد fieldها یا کل rootها را guard کنید.
  5. هرگز stack trace برنگردانید؛ type در problem کافی است (به Problem Details).
  6. هزینهٔ query را در GraphQL محدود کنید: عمق، پیچیدگی، persisted query برای کلاینت عمومی.

طراحی عمیق‌تر هویت و token خارج از این فصل است: Authentication و Authorization: RBAC, ABAC & Zero Trust؛ در مثال ما context هویت (Identity) tokenها را صادر می‌کند و Sales فقط اعتبارشان و مالکیت را بررسی می‌کند.

تست زبان منتشرشده مهم ​

به زبان ساده: تست‌هایی که وقتی به مصرف‌کننده قولی را می‌شکنید fail می‌شوند، نه فقط وقتی کد خودتان را می‌شکنید.

بدفهمی رایج: «تست واحد handlerها کافی است.» وقتی قرارداد دور می‌شود اینها همچنان سبزند. تست‌هایی دربارهٔ قرارداد لازم است.

لایهچه چیزی را می‌سنجدابزار اینجا
تست handlerstatus، هدر، بدنه، نوع problem برای هر قاعدهGo httptest، Laravel postJson
Lint قراردادفایل OpenAPI از قواعد خانه پیروی می‌کندruleset در Spectral
بررسی تغییر شکنندهفایل جدید در برابر فایل منتشرشدهoasdiff در CI
راستی‌آزمایی providerپاسخ‌های سرور واقعی با فایل می‌خواندSchemathesis، Dredd، Prism
Consumer-driven contractهر مصرف‌کننده می‌گوید چه استفاده می‌کند؛ provider باید همه را برآوردPact
بررسی schema (GraphQL)operationهای در حال استفاده با schema جدید هنوز معتبرندGraphQL Inspector، Apollo schema checks
بار و سوءاستفادهrate limit 429 می‌دهد، بدنهٔ بزرگ رد می‌شودk6، Vegeta

تست‌های Go در snippetها کل چرخه را می‌روند (ساخت، place خالی 422، افزودن خط، نبود If-Match 428، کهنه 412، تازه 200، 304، تعارض 409، 202 با replay کلید idempotency، poll وضعیت، keyset pagination) و نوع problem را assert می‌کنند نه متن پیام را. تست GraphQL assert می‌کند شش field محصول یک فراخوانی Catalog هزینه دارد و شکست کسب‌وکاری داده است (userErrors) بدون کلید errors.

consumer-driven contract (Pact) مدرکی است که تیم برای حذف یک فیلد لازم دارد: اگر در pact هیچ مصرف‌کننده‌ای ذکرش نشده، می‌شود حذفش کرد.

سازوکار (Mechanics) ​

چرخهٔ عمر یک درخواست فرمان حیاتی ​

Timeline: POST /orders/o1/placement in the Go server
1  ServeMux matches "POST /orders/{id}/placement" and sets r.PathValue("id")
2  place(): parse If-Match -> 428 problem when absent or malformed
3  Service.Place(ctx, id, expected): load order, compare version -> ErrVersionConflict
4  order.Place(now): invariants (draft, at least one line) -> ErrNotDraft / ErrEmptyOrder
5  Repository.Save: compare-and-set on version, version++
6  sendOrder: ETag = W/"<new version>", JSON from OrderDTO
7  any error -> fromError(err) -> Problem -> application/problem+json

مرجع status code و هدر حیاتی ​

کدنامچه وقت این API می‌فرستدRetry؟
200OKخواندن، فرمانی که تمام شد—
201Createdپیش‌نویس یا خط ساخته شد؛ Locationنه
202Acceptedدرخواست لغو ثبت شدpoll روی Location
204No Contentحذف پیش‌نویس (در snippet نیست)نه
304Not ModifiedIf-None-Match جور شد—
400Bad RequestJSON خراب، فیلد ناشناس، cursor بدنه، درخواست را درست کنید
401Unauthorizedtoken غایب یا نامعتبربعد از احراز دوباره
403Forbiddentoken scope لازم را نداردنه
404Not Foundid ناشناخته، یا منبع دیگرینه
409Conflictوضعیت اجازهٔ فرمان نمی‌دهدبعد از تغییر وضعیت
412Precondition FailedIf-Match کهنهدوباره بخوانید، بعد retry
422Unprocessable Contentدرست‌ساخت اما نامعتبر، یا قاعدهٔ کسب‌وکار روی محتوانه، داده را درست کنید
428Precondition RequiredIf-Match روی placement نیستهدر را اضافه کنید
429Too Many Requestsrate limit؛ Retry-Afterبله، بعد از تأخیر
500Internal Server Errorباگ؛ لاگ می‌شود، problem از نوع about:blankبا backoff، فقط idempotent
503Service Unavailableبار زیاد یا وابستگی خراب؛ Retry-Afterبا backoff

RFC 6585 دربارهٔ 429: پاسخ «MAY include a Retry-After header indicating how long to wait before making a new request».

کلید idempotency در ذخیره‌سازی حیاتی ​

sql
-- One row per accepted key. The unique constraint makes concurrent duplicates safe.
CREATE TABLE cancellation_requests (
  id          text PRIMARY KEY,
  order_id    text        NOT NULL,
  reason      text        NOT NULL,
  state       text        NOT NULL DEFAULT 'pending',
  detail      text,
  idem_key    text,
  created_at  timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX cancellation_requests_idem
  ON cancellation_requests (order_id, idem_key) WHERE idem_key IS NOT NULL;

-- The handler does: INSERT ... ON CONFLICT (order_id, idem_key) DO NOTHING RETURNING id;
-- no row returned -> SELECT the existing request and answer with it (same 202 body).

کلید را به صدازننده محدود کنید (اینجا سفارش؛ در حالت کلی شناسهٔ مصرف‌کننده به‌علاوهٔ کلید)، کلیدها را بعد از یک بازه منقضی کنید (Stripe کلید تا 255 نویسه را مستند کرده) و به‌اندازهٔ کافی از پاسخ اول نگه دارید تا تکرارش کنید. بدنهٔ متفاوت با همان کلید باید خطا باشد نه replay بی‌صدا.

GraphQL روی HTTP چطور حرکت می‌کند مهم ​

جنبهقاعده
Endpointیک path، /graphql، معمولاً POST با {"query", "variables", "operationName"}
Statusحتی برای خطای field 200؛ 400 برای سند ناخوانا یا نامعتبر؛ 401/403 از انتقال
اجراfieldهای query ممکن است موازی حل شوند؛ fieldهای سطح بالای mutation پشت‌سرهم
Batchingloader داخل یک operation دسته می‌کند؛ request batching چند operation را ادغام می‌کند (مگر لازم نشود پرهیز کنید)
کشPOST را کش HTTP نمی‌کند؛ persisted query با GET یا کش کلاینت بر پایهٔ id
Introspectionدر توسعه راحت؛ برای API عمومی در production محدود کنید
حدهاعمق، پیچیدگی، timeout، سقف pagination روی هر فهرست

Go ​

یک ماژول academy/api-realization-rest-graphql (gofmt و go vet تمیز، go test ./... پاس). لایه‌ها: sales خود context است (aggregate، Service برنامه، portها، adapterهای درحافظه)؛ rest و graph دو پیاده‌سازی از همان زبان‌اند؛ cmd/server هر دو را اجرا می‌کند.

دامنه و application service ​

Order فیلدهای خصوصی دارد؛ service تنها چیزی است که هر دو پیاده‌سازی صدا می‌زنند؛ portها (Catalog، Fulfilment، Repository، Cancellations) interfaceهایی کنار آن‌اند.

go
// Package sales is the Sales bounded context. Order is the aggregate root;
// the REST and GraphQL layers never see its fields, only what it exposes.
package sales

import (
	"errors"
	"fmt"
	"time"
)

// MaxQuantityPerLine is the Sales invariant shared by every chapter: 1..50
// units of one SKU per order line. The REST and GraphQL edges repeat it as
// shape validation; the aggregate is the authority.
const MaxQuantityPerLine = 50

type (
	// OrderID is the identity of the Order aggregate.
	OrderID string
	// CustomerID references the Identity context's customer by id only.
	CustomerID string
	// SKU references a Catalog product by id only.
	SKU string
)

// Status is the order state machine.
type Status string

const (
	Draft     Status = "draft"
	Placed    Status = "placed"
	Cancelled Status = "cancelled"
)

var (
	ErrNotFound         = errors.New("not found")
	ErrNotDraft         = errors.New("only a draft order can be edited")
	ErrEmptyOrder       = errors.New("an order needs at least one line")
	ErrBadQuantity      = fmt.Errorf("quantity must be between 1 and %d", MaxQuantityPerLine)
	ErrUnknownProduct   = errors.New("unknown product")
	ErrVersionConflict  = errors.New("order changed since you read it")
	ErrNotCancellable   = errors.New("order cannot be cancelled in its current state")
	ErrAlreadyCancelled = errors.New("order is already cancelled")
)

// Money is a value object in minor units.
type Money struct {
	Minor    int64
	Currency string
}

// Line is a read-only view of one order line.
type Line struct {
	SKU            SKU
	Quantity       int
	UnitPriceMinor int64
}

// Order is the aggregate root. Fields are private: only methods change state.
type Order struct {
	id       OrderID
	customer CustomerID
	currency string
	status   Status
	lines    []Line
	placedAt time.Time
	version  int
	seq      int64 // creation order, used as the keyset cursor
}

// NewOrder starts a draft order.
func NewOrder(id OrderID, customer CustomerID, currency string) *Order {
	return &Order{id: id, customer: customer, currency: currency, status: Draft}
}

// AddLine adds or merges a line while the order is a draft.
func (o *Order) AddLine(sku SKU, qty int, unitPriceMinor int64) error {
	if o.status != Draft {
		return ErrNotDraft
	}
	if qty < 1 || qty > MaxQuantityPerLine {
		return ErrBadQuantity
	}
	for i := range o.lines {
		if o.lines[i].SKU == sku {
			if o.lines[i].Quantity+qty > MaxQuantityPerLine {
				return ErrBadQuantity
			}
			o.lines[i].Quantity += qty
			return nil
		}
	}
	o.lines = append(o.lines, Line{SKU: sku, Quantity: qty, UnitPriceMinor: unitPriceMinor})
	return nil
}

// Place commits the order.
func (o *Order) Place(now time.Time) error {
	if o.status != Draft {
		return ErrNotDraft
	}
	if len(o.lines) == 0 {
		return ErrEmptyOrder
	}
	o.status = Placed
	o.placedAt = now
	return nil
}

// Cancel moves a draft or placed order to cancelled.
func (o *Order) Cancel() error {
	switch o.status {
	case Cancelled:
		return ErrAlreadyCancelled
	case Draft, Placed:
		o.status = Cancelled
		return nil
	}
	return ErrNotCancellable
}

// Total is derived from the lines.
func (o *Order) Total() Money {
	var t int64
	for _, l := range o.lines {
		t += l.UnitPriceMinor * int64(l.Quantity)
	}
	return Money{Minor: t, Currency: o.currency}
}

func (o *Order) ID() OrderID          { return o.id }
func (o *Order) Customer() CustomerID { return o.customer }
func (o *Order) Currency() string     { return o.currency }
func (o *Order) Status() Status       { return o.status }
func (o *Order) Version() int         { return o.version }
func (o *Order) PlacedAt() time.Time  { return o.placedAt }
func (o *Order) Seq() int64           { return o.seq }

// Lines returns a copy of the lines.
func (o *Order) Lines() []Line { return append([]Line(nil), o.lines...) }
go
package sales

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"time"
)

// Product is Catalog's published view of a product (an ACL-friendly shape).
type Product struct {
	SKU            SKU
	Name           string
	UnitPriceMinor int64
}

// Catalog is the port to the Catalog context. Batch lookup exists so that
// GraphQL can avoid N+1 calls.
type Catalog interface {
	Products(ctx context.Context, skus []SKU) (map[SKU]Product, error)
}

// Fulfilment is the port to the Fulfilment context.
type Fulfilment interface {
	// ReleaseStock asks Fulfilment to release reservations for an order.
	ReleaseStock(ctx context.Context, id OrderID) error
}

// Repository loads and saves whole aggregates.
type Repository interface {
	Get(ctx context.Context, id OrderID) (*Order, error)
	// Save inserts (version 0) or updates with a compare-and-set on version.
	Save(ctx context.Context, o *Order) error
	// List returns orders in creation order after the cursor sequence.
	List(ctx context.Context, q ListQuery) ([]*Order, error)
}

// ListQuery is a keyset query: filters, the last seen sequence, and a limit.
type ListQuery struct {
	Customer CustomerID
	Status   Status // empty means any
	After    int64
	Limit    int
}

// CancellationState is the lifecycle of a cancellation request resource.
type CancellationState string

const (
	CancellationPending   CancellationState = "pending"
	CancellationCompleted CancellationState = "completed"
	CancellationRejected  CancellationState = "rejected"
)

// CancellationRequest is a first-class record of the intent to cancel.
// It exists because cancelling needs Fulfilment, so the answer is not instant.
type CancellationRequest struct {
	ID      string
	OrderID OrderID
	Reason  string
	State   CancellationState
	Detail  string
}

// Cancellations stores requests and remembers idempotency keys.
type Cancellations interface {
	Create(ctx context.Context, key string, r CancellationRequest) (CancellationRequest, bool, error)
	Get(ctx context.Context, id string) (CancellationRequest, error)
	Update(ctx context.Context, r CancellationRequest) error
}

// Service is the application layer: one method per use case.
type Service struct {
	Orders     Repository
	Cancels    Cancellations
	Catalog    Catalog
	Fulfilment Fulfilment
	Now        func() time.Time
	NewID      func() string
}

func (s *Service) id(prefix string) string {
	if s.NewID != nil {
		return prefix + s.NewID()
	}
	b := make([]byte, 8)
	_, _ = rand.Read(b)
	return prefix + hex.EncodeToString(b)
}

func (s *Service) now() time.Time {
	if s.Now != nil {
		return s.Now()
	}
	return time.Now().UTC()
}

// CreateDraft opens a new draft order.
func (s *Service) CreateDraft(ctx context.Context, c CustomerID, currency string) (*Order, error) {
	o := NewOrder(OrderID(s.id("ord_")), c, currency)
	if err := s.Orders.Save(ctx, o); err != nil {
		return nil, err
	}
	return s.Orders.Get(ctx, o.ID())
}

// load reads the order and enforces the caller's expected version (0 = skip).
func (s *Service) load(ctx context.Context, id OrderID, expected int) (*Order, error) {
	o, err := s.Orders.Get(ctx, id)
	if err != nil {
		return nil, err
	}
	if expected != 0 && o.Version() != expected {
		return nil, ErrVersionConflict
	}
	return o, nil
}

// AddLine prices the line from Catalog, never from the client.
func (s *Service) AddLine(ctx context.Context, id OrderID, sku SKU, qty, expected int) (*Order, error) {
	o, err := s.load(ctx, id, expected)
	if err != nil {
		return nil, err
	}
	ps, err := s.Catalog.Products(ctx, []SKU{sku})
	if err != nil {
		return nil, err
	}
	p, ok := ps[sku]
	if !ok {
		return nil, fmt.Errorf("%w: %s", ErrUnknownProduct, sku)
	}
	if err := o.AddLine(sku, qty, p.UnitPriceMinor); err != nil {
		return nil, err
	}
	if err := s.Orders.Save(ctx, o); err != nil {
		return nil, err
	}
	return s.Orders.Get(ctx, id)
}

// Place is the "place order" command.
func (s *Service) Place(ctx context.Context, id OrderID, expected int) (*Order, error) {
	o, err := s.load(ctx, id, expected)
	if err != nil {
		return nil, err
	}
	if err := o.Place(s.now()); err != nil {
		return nil, err
	}
	if err := s.Orders.Save(ctx, o); err != nil {
		return nil, err
	}
	return s.Orders.Get(ctx, id)
}

// RequestCancellation records the intent and returns at once. Replaying the
// same key returns the same request instead of creating a second one.
func (s *Service) RequestCancellation(ctx context.Context, id OrderID, reason, key string) (CancellationRequest, error) {
	o, err := s.Orders.Get(ctx, id)
	if err != nil {
		return CancellationRequest{}, err
	}
	if o.Status() == Cancelled {
		return CancellationRequest{}, ErrAlreadyCancelled
	}
	r, _, err := s.Cancels.Create(ctx, key, CancellationRequest{
		ID: s.id("can_"), OrderID: id, Reason: reason, State: CancellationPending,
	})
	return r, err
}

// ProcessCancellation is the background step: it asks Fulfilment to release
// stock, then cancels the aggregate, then closes the request.
func (s *Service) ProcessCancellation(ctx context.Context, reqID string) error {
	r, err := s.Cancels.Get(ctx, reqID)
	if err != nil {
		return err
	}
	if r.State != CancellationPending {
		return nil // already handled: processing is idempotent
	}
	if err := s.Fulfilment.ReleaseStock(ctx, r.OrderID); err != nil {
		r.State, r.Detail = CancellationRejected, err.Error()
		return s.Cancels.Update(ctx, r)
	}
	o, err := s.Orders.Get(ctx, r.OrderID)
	if err != nil {
		return err
	}
	if err := o.Cancel(); err != nil {
		r.State, r.Detail = CancellationRejected, err.Error()
		return s.Cancels.Update(ctx, r)
	}
	if err := s.Orders.Save(ctx, o); err != nil {
		return err
	}
	r.State = CancellationCompleted
	return s.Cancels.Update(ctx, r)
}

// GetCancellation reads the status resource.
func (s *Service) GetCancellation(ctx context.Context, id string) (CancellationRequest, error) {
	return s.Cancels.Get(ctx, id)
}

// GetOrder reads one order.
func (s *Service) GetOrder(ctx context.Context, id OrderID) (*Order, error) {
	return s.Orders.Get(ctx, id)
}

// ListOrders runs a keyset query.
func (s *Service) ListOrders(ctx context.Context, q ListQuery) ([]*Order, error) {
	return s.Orders.List(ctx, q)
}

REST: DTO، Problem Details و handlerها ​

DTOها و problemها بالاتر آمدند. handlerها از الگوهای method-و-wildcard در ServeMux نسخهٔ Go 1.22 استفاده می‌کنند ("POST /orders/{id}/placement")؛ با chi همین routeها به‌صورت r.Post("/orders/{id}/placement", h) و chi.URLParam(r, "id") نوشته می‌شوند.

go
package rest

import (
	"encoding/base64"
	"encoding/json"
	"net/http"
	"strconv"

	"academy/api-realization-rest-graphql/sales"
)

// Server wires the use cases to HTTP. Go 1.22+ ServeMux patterns are enough;
// chi.Router works the same way (r.Post("/orders/{id}/placement", ...)).
type Server struct{ Svc *sales.Service }

// Handler returns the routed http.Handler.
func (s *Server) Handler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /orders", s.createOrder)
	mux.HandleFunc("GET /orders", s.listOrders)
	mux.HandleFunc("GET /orders/{id}", s.getOrder)
	mux.HandleFunc("POST /orders/{id}/lines", s.addLine)
	mux.HandleFunc("POST /orders/{id}/placement", s.place)
	mux.HandleFunc("POST /orders/{id}/cancellation-requests", s.requestCancellation)
	mux.HandleFunc("GET /cancellation-requests/{id}", s.getCancellation)
	return mux
}

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(v)
}

func decode(w http.ResponseWriter, r *http.Request, v any) bool {
	dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
	dec.DisallowUnknownFields()
	if err := dec.Decode(v); err != nil {
		writeProblem(w, r, Problem{Type: problemBase + "malformed-body", Title: "Malformed request body",
			Status: http.StatusBadRequest, Detail: err.Error()})
		return false
	}
	return true
}

func sendOrder(w http.ResponseWriter, status int, o *sales.Order) {
	w.Header().Set("ETag", etag(o))
	writeJSON(w, status, toOrderDTO(o))
}

func (s *Server) createOrder(w http.ResponseWriter, r *http.Request) {
	var in struct {
		CustomerID string `json:"customerId"`
		Currency   string `json:"currency"`
	}
	if !decode(w, r, &in) {
		return
	}
	var errs []FieldError
	if in.CustomerID == "" {
		errs = append(errs, FieldError{"/customerId", "is required"})
	}
	if len(in.Currency) != 3 {
		errs = append(errs, FieldError{"/currency", "must be a 3-letter ISO 4217 code"})
	}
	if errs != nil {
		writeProblem(w, r, Problem{Type: problemBase + "validation-failed", Title: "Your request is invalid",
			Status: http.StatusUnprocessableEntity, Errors: errs})
		return
	}
	o, err := s.Svc.CreateDraft(r.Context(), sales.CustomerID(in.CustomerID), in.Currency)
	if err != nil {
		writeProblem(w, r, fromError(err))
		return
	}
	w.Header().Set("Location", "/orders/"+string(o.ID()))
	sendOrder(w, http.StatusCreated, o)
}

func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
	o, err := s.Svc.GetOrder(r.Context(), sales.OrderID(r.PathValue("id")))
	if err != nil {
		writeProblem(w, r, fromError(err))
		return
	}
	if inm := r.Header.Get("If-None-Match"); inm != "" && inm == etag(o) {
		w.Header().Set("ETag", etag(o))
		w.WriteHeader(http.StatusNotModified)
		return
	}
	w.Header().Set("Cache-Control", "private, max-age=0, must-revalidate")
	sendOrder(w, http.StatusOK, o)
}

func (s *Server) listOrders(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	limit, _ := strconv.Atoi(q.Get("limit"))
	if limit < 1 || limit > 100 {
		limit = 20
	}
	var after int64
	if c := q.Get("cursor"); c != "" {
		raw, err := base64.RawURLEncoding.DecodeString(c)
		if err == nil {
			after, err = strconv.ParseInt(string(raw), 10, 64)
		}
		if err != nil {
			writeProblem(w, r, Problem{Type: problemBase + "validation-failed", Title: "Your request is invalid",
				Status: http.StatusBadRequest, Detail: "cursor is not valid"})
			return
		}
	}
	orders, err := s.Svc.ListOrders(r.Context(), sales.ListQuery{
		Customer: sales.CustomerID(q.Get("customerId")), Status: sales.Status(q.Get("status")),
		After: after, Limit: limit + 1, // one extra row tells us whether a next page exists
	})
	if err != nil {
		writeProblem(w, r, fromError(err))
		return
	}
	page := OrderPage{Items: []OrderDTO{}}
	for i, o := range orders {
		if i == limit {
			last := orders[limit-1].Seq()
			page.NextCursor = base64.RawURLEncoding.EncodeToString([]byte(strconv.FormatInt(last, 10)))
			break
		}
		page.Items = append(page.Items, toOrderDTO(o))
	}
	writeJSON(w, http.StatusOK, page)
}

func (s *Server) addLine(w http.ResponseWriter, r *http.Request) {
	var in struct {
		SKU      string `json:"sku"`
		Quantity int    `json:"quantity"`
	}
	if !decode(w, r, &in) {
		return
	}
	expected, _ := parseETag(r.Header.Get("If-Match")) // optional here
	o, err := s.Svc.AddLine(r.Context(), sales.OrderID(r.PathValue("id")), sales.SKU(in.SKU), in.Quantity, expected)
	if err != nil {
		writeProblem(w, r, fromError(err))
		return
	}
	w.Header().Set("Location", "/orders/"+string(o.ID())+"/lines/"+in.SKU)
	sendOrder(w, http.StatusCreated, o)
}

// place requires If-Match: money-moving commands must not run on a stale view.
func (s *Server) place(w http.ResponseWriter, r *http.Request) {
	expected, ok := parseETag(r.Header.Get("If-Match"))
	if !ok {
		writeProblem(w, r, Problem{Type: problemBase + "precondition-required", Title: "If-Match header is required",
			Status: http.StatusPreconditionRequired})
		return
	}
	o, err := s.Svc.Place(r.Context(), sales.OrderID(r.PathValue("id")), expected)
	if err != nil {
		writeProblem(w, r, fromError(err))
		return
	}
	sendOrder(w, http.StatusOK, o)
}

// requestCancellation answers 202: the request is accepted, not yet done.
func (s *Server) requestCancellation(w http.ResponseWriter, r *http.Request) {
	var in struct {
		Reason string `json:"reason"`
	}
	if !decode(w, r, &in) {
		return
	}
	req, err := s.Svc.RequestCancellation(r.Context(), sales.OrderID(r.PathValue("id")), in.Reason, r.Header.Get("Idempotency-Key"))
	if err != nil {
		writeProblem(w, r, fromError(err))
		return
	}
	w.Header().Set("Location", "/cancellation-requests/"+req.ID)
	w.Header().Set("Retry-After", "1")
	writeJSON(w, http.StatusAccepted, toCancellationDTO(req))
}

func (s *Server) getCancellation(w http.ResponseWriter, r *http.Request) {
	req, err := s.Svc.GetCancellation(r.Context(), r.PathValue("id"))
	if err != nil {
		writeProblem(w, r, fromError(err))
		return
	}
	writeJSON(w, http.StatusOK, toCancellationDTO(req))
}

تست کل قرارداد را می‌رود:

go
package rest_test

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"academy/api-realization-rest-graphql/rest"
	"academy/api-realization-rest-graphql/sales"
)

func newServer(t *testing.T) (*httptest.Server, *sales.Service) {
	t.Helper()
	n := 0
	svc := &sales.Service{
		Orders:  sales.NewMemoryOrders(),
		Cancels: sales.NewMemoryCancellations(),
		Catalog: &sales.StaticCatalog{Items: map[sales.SKU]sales.Product{
			"SKU-1": {SKU: "SKU-1", Name: "Mug", UnitPriceMinor: 1250},
		}},
		Fulfilment: sales.NoopFulfilment{},
		NewID:      func() string { n++; return fmt.Sprint(n) },
	}
	ts := httptest.NewServer((&rest.Server{Svc: svc}).Handler())
	t.Cleanup(ts.Close)
	return ts, svc
}

func do(t *testing.T, method, url, body string, hdr map[string]string) *http.Response {
	t.Helper()
	req, _ := http.NewRequest(method, url, strings.NewReader(body))
	for k, v := range hdr {
		req.Header.Set(k, v)
	}
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { res.Body.Close() })
	return res
}

func decode[T any](t *testing.T, res *http.Response) T {
	t.Helper()
	var v T
	if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
		t.Fatal(err)
	}
	return v
}

func TestOrderLifecycleOverHTTP(t *testing.T) {
	ts, svc := newServer(t)

	res := do(t, "POST", ts.URL+"/orders", `{"customerId":"c1","currency":"EUR"}`, nil)
	if res.StatusCode != 201 || res.Header.Get("Location") != "/orders/ord_1" {
		t.Fatalf("create: %d %q", res.StatusCode, res.Header.Get("Location"))
	}
	etag := res.Header.Get("ETag")

	// Placing an empty order is a business-rule problem, not a 500.
	res = do(t, "POST", ts.URL+"/orders/ord_1/placement", "", map[string]string{"If-Match": etag})
	p := decode[rest.Problem](t, res)
	if res.StatusCode != 422 || p.Type != "https://api.example.com/problems/order-empty" ||
		res.Header.Get("Content-Type") != "application/problem+json" {
		t.Fatalf("empty place: %d %+v", res.StatusCode, p)
	}

	res = do(t, "POST", ts.URL+"/orders/ord_1/lines", `{"sku":"SKU-1","quantity":2}`, nil)
	o := decode[rest.OrderDTO](t, res)
	if res.StatusCode != 201 || o.Total.AmountMinor != 2500 {
		t.Fatalf("add line: %d %+v", res.StatusCode, o)
	}
	if _, ok := o.Links["placement"]; !ok {
		t.Fatal("draft order must advertise the placement link")
	}

	// Missing If-Match: 428. Stale If-Match: 412. Fresh: 200.
	if res = do(t, "POST", ts.URL+"/orders/ord_1/placement", "", nil); res.StatusCode != 428 {
		t.Fatalf("missing If-Match: %d", res.StatusCode)
	}
	if res = do(t, "POST", ts.URL+"/orders/ord_1/placement", "", map[string]string{"If-Match": etag}); res.StatusCode != 412 {
		t.Fatalf("stale If-Match: %d", res.StatusCode)
	}
	fresh := do(t, "GET", ts.URL+"/orders/ord_1", "", nil).Header.Get("ETag")
	res = do(t, "POST", ts.URL+"/orders/ord_1/placement", "", map[string]string{"If-Match": fresh})
	if o = decode[rest.OrderDTO](t, res); res.StatusCode != 200 || o.Status != "placed" {
		t.Fatalf("place: %d %+v", res.StatusCode, o)
	}

	// Conditional GET: 304 when nothing changed.
	cur := res.Header.Get("ETag")
	if res = do(t, "GET", ts.URL+"/orders/ord_1", "", map[string]string{"If-None-Match": cur}); res.StatusCode != 304 {
		t.Fatalf("conditional GET: %d", res.StatusCode)
	}

	// A placed order can no longer take lines: 409 with a stable problem type.
	res = do(t, "POST", ts.URL+"/orders/ord_1/lines", `{"sku":"SKU-1","quantity":1}`, nil)
	if p = decode[rest.Problem](t, res); res.StatusCode != 409 || !strings.HasSuffix(p.Type, "order-not-editable") {
		t.Fatalf("edit placed: %d %+v", res.StatusCode, p)
	}

	// Eventual consistency made visible: 202 + Location, then poll.
	hdr := map[string]string{"Idempotency-Key": "k-1"}
	res = do(t, "POST", ts.URL+"/orders/ord_1/cancellation-requests", `{"reason":"changed my mind"}`, hdr)
	c := decode[rest.CancellationDTO](t, res)
	if res.StatusCode != 202 || res.Header.Get("Location") != "/cancellation-requests/can_2" || c.State != "pending" {
		t.Fatalf("cancel: %d %+v", res.StatusCode, c)
	}
	// The same key returns the same request, not a second one.
	res = do(t, "POST", ts.URL+"/orders/ord_1/cancellation-requests", `{"reason":"changed my mind"}`, hdr)
	if res.Header.Get("Location") != "/cancellation-requests/can_2" {
		t.Fatalf("replay created a new request: %q", res.Header.Get("Location"))
	}
	if c = decode[rest.CancellationDTO](t, do(t, "GET", ts.URL+"/cancellation-requests/can_2", "", nil)); c.State != "pending" {
		t.Fatalf("before worker: %s", c.State)
	}
	if err := svc.ProcessCancellation(context.Background(), "can_2"); err != nil {
		t.Fatal(err)
	}
	c = decode[rest.CancellationDTO](t, do(t, "GET", ts.URL+"/cancellation-requests/can_2", "", nil))
	o = decode[rest.OrderDTO](t, do(t, "GET", ts.URL+"/orders/ord_1", "", nil))
	if c.State != "completed" || o.Status != "cancelled" {
		t.Fatalf("after worker: %s / %s", c.State, o.Status)
	}
}

func TestValidationAndKeysetPagination(t *testing.T) {
	ts, _ := newServer(t)
	res := do(t, "POST", ts.URL+"/orders", `{"currency":"EU"}`, nil)
	p := decode[rest.Problem](t, res)
	if res.StatusCode != 422 || len(p.Errors) != 2 || p.Errors[0].Pointer != "/customerId" {
		t.Fatalf("validation: %d %+v", res.StatusCode, p)
	}
	for range 3 {
		do(t, "POST", ts.URL+"/orders", `{"customerId":"c9","currency":"EUR"}`, nil)
	}
	page := decode[rest.OrderPage](t, do(t, "GET", ts.URL+"/orders?customerId=c9&limit=2", "", nil))
	if len(page.Items) != 2 || page.NextCursor == "" {
		t.Fatalf("page 1: %+v", page)
	}
	page2 := decode[rest.OrderPage](t, do(t, "GET", ts.URL+"/orders?customerId=c9&limit=2&cursor="+page.NextCursor, "", nil))
	if len(page2.Items) != 1 || page2.NextCursor != "" {
		t.Fatalf("page 2: %+v", page2)
	}
	if res = do(t, "GET", ts.URL+"/orders/nope", "", nil); res.StatusCode != 404 {
		t.Fatalf("404: %d", res.StatusCode)
	}
}

GraphQL با gqlgen ​

gqlgen generate فایل gqlgen.yml و SDL را می‌خواند و generated.go و model/models_gen.go را می‌نویسد؛ بخش دست‌نویس resolverها و loader است. OrderLine.product به‌صورت field با resolver تنظیم شده، و dataloader از همین‌جا وصل می‌شود.

yml
schema:
  - graph/*.graphql
exec:
  filename: graph/generated.go
  package: graph
model:
  filename: graph/model/models_gen.go
  package: model
resolver:
  layout: follow-schema
  dir: graph
  package: graph
  filename_template: "{name}.resolvers.go"
autobind: []
models:
  ID:
    model: github.com/99designs/gqlgen/graphql.String
  DateTime:
    model: github.com/99designs/gqlgen/graphql.Time
  OrderLine:
    fields:
      product:
        resolver: true
go
package graph

// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98

import (
	"academy/api-realization-rest-graphql/graph/model"
	"academy/api-realization-rest-graphql/sales"
	"context"
	"encoding/base64"
	"errors"
	"strconv"
)

// CreateDraftOrder is the resolver for the createDraftOrder field.
func (r *mutationResolver) CreateDraftOrder(ctx context.Context, input model.CreateDraftOrderInput) (*model.CreateDraftOrderPayload, error) {
	o, err := r.Svc.CreateDraft(ctx, sales.CustomerID(input.CustomerID), input.Currency)
	if ue, ok := userError(err); ok {
		return &model.CreateDraftOrderPayload{UserErrors: []*model.UserError{ue}}, nil
	} else if err != nil {
		return nil, err
	}
	return &model.CreateDraftOrderPayload{Order: toOrder(o), UserErrors: []*model.UserError{}}, nil
}

// AddOrderLine is the resolver for the addOrderLine field.
func (r *mutationResolver) AddOrderLine(ctx context.Context, input model.AddOrderLineInput) (*model.AddOrderLinePayload, error) {
	expected := 0
	if input.ExpectedVersion != nil {
		expected = *input.ExpectedVersion
	}
	o, err := r.Svc.AddLine(ctx, sales.OrderID(input.OrderID), sales.SKU(input.Sku), input.Quantity, expected)
	if ue, ok := userError(err); ok {
		return &model.AddOrderLinePayload{UserErrors: []*model.UserError{ue}}, nil
	} else if err != nil {
		return nil, err
	}
	return &model.AddOrderLinePayload{Order: toOrder(o), UserErrors: []*model.UserError{}}, nil
}

// PlaceOrder is the resolver for the placeOrder field.
func (r *mutationResolver) PlaceOrder(ctx context.Context, input model.PlaceOrderInput) (*model.PlaceOrderPayload, error) {
	o, err := r.Svc.Place(ctx, sales.OrderID(input.OrderID), input.ExpectedVersion)
	if ue, ok := userError(err); ok {
		return &model.PlaceOrderPayload{UserErrors: []*model.UserError{ue}}, nil
	} else if err != nil {
		return nil, err
	}
	return &model.PlaceOrderPayload{Order: toOrder(o), UserErrors: []*model.UserError{}}, nil
}

// RequestOrderCancellation is the resolver for the requestOrderCancellation field.
func (r *mutationResolver) RequestOrderCancellation(ctx context.Context, input model.RequestOrderCancellationInput) (*model.RequestOrderCancellationPayload, error) {
	key := ""
	if input.IdempotencyKey != nil {
		key = *input.IdempotencyKey
	}
	req, err := r.Svc.RequestCancellation(ctx, sales.OrderID(input.OrderID), input.Reason, key)
	if ue, ok := userError(err); ok {
		return &model.RequestOrderCancellationPayload{UserErrors: []*model.UserError{ue}}, nil
	} else if err != nil {
		return nil, err
	}
	return &model.RequestOrderCancellationPayload{Request: toRequest(req), UserErrors: []*model.UserError{}}, nil
}

// Product is the resolver for the product field. It never calls Catalog
// directly: the loader batches every product requested in this operation.
func (r *orderLineResolver) Product(ctx context.Context, obj *model.OrderLine) (*model.Product, error) {
	return For(ctx).Product.Load(ctx, obj.Sku)
}

// Order is the resolver for the order field.
func (r *queryResolver) Order(ctx context.Context, id string) (*model.Order, error) {
	o, err := r.Svc.GetOrder(ctx, sales.OrderID(id))
	if errors.Is(err, sales.ErrNotFound) {
		return nil, nil // a missing node is null, not an error
	}
	if err != nil {
		return nil, err
	}
	return toOrder(o), nil
}

// Orders is the resolver for the orders field (Relay-style connection).
func (r *queryResolver) Orders(ctx context.Context, customerID string, status *model.OrderStatus, first *int, after *string) (*model.OrderConnection, error) {
	limit := 20
	if first != nil && *first > 0 && *first <= 100 {
		limit = *first
	}
	var cursor int64
	if after != nil {
		raw, err := base64.RawURLEncoding.DecodeString(*after)
		if err == nil {
			cursor, err = strconv.ParseInt(string(raw), 10, 64)
		}
		if err != nil {
			return nil, errors.New("invalid cursor")
		}
	}
	q := sales.ListQuery{Customer: sales.CustomerID(customerID), After: cursor, Limit: limit + 1}
	if status != nil {
		q.Status = sales.Status(lower(string(*status)))
	}
	rows, err := r.Svc.ListOrders(ctx, q)
	if err != nil {
		return nil, err
	}
	conn := &model.OrderConnection{Edges: []*model.OrderEdge{}, PageInfo: &model.PageInfo{}}
	for i, o := range rows {
		if i == limit {
			conn.PageInfo.HasNextPage = true
			break
		}
		c := base64.RawURLEncoding.EncodeToString([]byte(strconv.FormatInt(o.Seq(), 10)))
		conn.Edges = append(conn.Edges, &model.OrderEdge{Cursor: c, Node: toOrder(o)})
		conn.PageInfo.EndCursor = &c
	}
	return conn, nil
}

// CancellationRequest is the resolver for the cancellationRequest field.
func (r *queryResolver) CancellationRequest(ctx context.Context, id string) (*model.CancellationRequest, error) {
	req, err := r.Svc.GetCancellation(ctx, id)
	if errors.Is(err, sales.ErrNotFound) {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return toRequest(req), nil
}

// Mutation returns MutationResolver implementation.
func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} }

// OrderLine returns OrderLineResolver implementation.
func (r *Resolver) OrderLine() OrderLineResolver { return &orderLineResolver{r} }

// Query returns QueryResolver implementation.
func (r *Resolver) Query() QueryResolver { return &queryResolver{r} }

type (
	mutationResolver  struct{ *Resolver }
	orderLineResolver struct{ *Resolver }
	queryResolver     struct{ *Resolver }
)
go
package graph

import (
	"errors"

	"academy/api-realization-rest-graphql/graph/model"
	"academy/api-realization-rest-graphql/sales"
)

// toOrder maps the aggregate to the GraphQL type. Types come from the
// published model, not from table columns.
func toOrder(o *sales.Order) *model.Order {
	out := &model.Order{
		ID: string(o.ID()), CustomerID: string(o.Customer()), Version: o.Version(),
		Status: model.OrderStatus(upper(string(o.Status()))),
		Total:  &model.Money{AmountMinor: int(o.Total().Minor), Currency: o.Total().Currency},
	}
	if !o.PlacedAt().IsZero() {
		t := o.PlacedAt()
		out.PlacedAt = &t
	}
	for _, l := range o.Lines() {
		out.Lines = append(out.Lines, &model.OrderLine{
			Sku: string(l.SKU), Quantity: l.Quantity,
			UnitPrice: &model.Money{AmountMinor: int(l.UnitPriceMinor), Currency: o.Currency()},
		})
	}
	return out
}

func toRequest(r sales.CancellationRequest) *model.CancellationRequest {
	out := &model.CancellationRequest{
		ID: r.ID, OrderID: string(r.OrderID), Reason: r.Reason,
		State: model.CancellationState(upper(string(r.State))),
	}
	if r.Detail != "" {
		out.Detail = &r.Detail
	}
	return out
}

// userError turns a business failure into data the client can render.
// Anything unexpected is returned as a real GraphQL error instead.
func userError(err error) (*model.UserError, bool) {
	codes := map[error]string{
		sales.ErrNotDraft: "ORDER_NOT_EDITABLE", sales.ErrEmptyOrder: "ORDER_EMPTY",
		sales.ErrBadQuantity: "INVALID_QUANTITY", sales.ErrUnknownProduct: "UNKNOWN_PRODUCT",
		sales.ErrVersionConflict: "STALE_VERSION", sales.ErrNotFound: "NOT_FOUND",
		sales.ErrAlreadyCancelled: "ALREADY_CANCELLED", sales.ErrNotCancellable: "NOT_CANCELLABLE",
	}
	for target, code := range codes {
		if errors.Is(err, target) {
			return &model.UserError{Code: code, Message: err.Error()}, true
		}
	}
	return nil, false
}

func upper(s string) string {
	b := []byte(s)
	for i, c := range b {
		if c >= 'a' && c <= 'z' {
			b[i] = c - 32
		}
	}
	return string(b)
}

func lower(s string) string {
	b := []byte(s)
	for i, c := range b {
		if c >= 'A' && c <= 'Z' {
			b[i] = c + 32
		}
	}
	return string(b)
}
go
package graph_test

import (
	"fmt"
	"testing"

	"github.com/99designs/gqlgen/client"
	"github.com/99designs/gqlgen/graphql/handler"

	"academy/api-realization-rest-graphql/graph"
	"academy/api-realization-rest-graphql/sales"
)

func setup(t *testing.T) (*client.Client, *sales.StaticCatalog) {
	t.Helper()
	n := 0
	cat := &sales.StaticCatalog{Items: map[sales.SKU]sales.Product{
		"SKU-1": {SKU: "SKU-1", Name: "Mug", UnitPriceMinor: 1250},
		"SKU-2": {SKU: "SKU-2", Name: "Plate", UnitPriceMinor: 900},
	}}
	svc := &sales.Service{Orders: sales.NewMemoryOrders(), Cancels: sales.NewMemoryCancellations(),
		Catalog: cat, Fulfilment: sales.NoopFulfilment{}, NewID: func() string { n++; return fmt.Sprint(n) }}
	srv := handler.NewDefaultServer(graph.NewExecutableSchema(graph.Config{Resolvers: &graph.Resolver{Svc: svc}}))
	return client.New(graph.Middleware(cat, srv)), cat
}

func TestOrdersWithProductsUseOneCatalogBatch(t *testing.T) {
	c, cat := setup(t)
	var created struct {
		CreateDraftOrder struct{ Order struct{ ID string } }
	}
	var added struct {
		AddOrderLine struct{ UserErrors []struct{ Code string } }
	}
	for range 3 {
		c.MustPost(`mutation { createDraftOrder(input:{customerId:"c1", currency:"EUR"}) { order { id } } }`, &created)
		for _, sku := range []string{"SKU-1", "SKU-2"} {
			q := fmt.Sprintf(`mutation { addOrderLine(input:{orderId:%q, sku:%q, quantity:1}) { userErrors { code } } }`,
				created.CreateDraftOrder.Order.ID, sku)
			c.MustPost(q, &added)
		}
	}
	cat.Calls = 0 // count only the read below (the writes priced lines already)

	var resp struct {
		Orders struct {
			Edges []struct {
				Node struct {
					Lines []struct{ Product struct{ Name string } }
				}
			}
			PageInfo struct{ HasNextPage bool }
		}
	}
	c.MustPost(`{ orders(customerId:"c1", first:10) { edges { node { lines { product { name } } } } pageInfo { hasNextPage } } }`, &resp)
	if len(resp.Orders.Edges) != 3 {
		t.Fatalf("want 3 orders, got %d", len(resp.Orders.Edges))
	}
	if got := resp.Orders.Edges[0].Node.Lines[1].Product.Name; got != "Plate" {
		t.Fatalf("product name %q", got)
	}
	if cat.Calls != 1 {
		t.Fatalf("6 product fields must cost 1 catalog call, got %d", cat.Calls)
	}
}

func TestBusinessFailureIsDataNotError(t *testing.T) {
	c, _ := setup(t)
	var created struct {
		CreateDraftOrder struct{ Order struct{ ID string } }
	}
	c.MustPost(`mutation { createDraftOrder(input:{customerId:"c1", currency:"EUR"}) { order { id } } }`, &created)
	var placed struct {
		PlaceOrder struct {
			Order      *struct{ ID string }
			UserErrors []struct{ Code, Message string }
		}
	}
	q := fmt.Sprintf(`mutation { placeOrder(input:{orderId:%q, expectedVersion:1}) { order { id } userErrors { code message } } }`,
		created.CreateDraftOrder.Order.ID)
	if err := c.Post(q, &placed); err != nil {
		t.Fatalf("a business rule must not be a GraphQL error: %v", err)
	}
	if placed.PlaceOrder.Order != nil || len(placed.PlaceOrder.UserErrors) != 1 || placed.PlaceOrder.UserErrors[0].Code != "ORDER_EMPTY" {
		t.Fatalf("%+v", placed.PlaceOrder)
	}
}

زاویهٔ Go ​

  • net/http با الگوهای ServeMux برای بیشتر سرویس‌ها مسیریابی را پوشش می‌دهد؛ chi گروه middleware و URLParam اضافه می‌کند؛ هر دو http.Handler می‌دهند.
  • encoding/json با DisallowUnknownFields و http.MaxBytesReader یک خط دفاع در برابر کلاینت شلخته و بدنهٔ عظیم است.
  • خطا مقدار است: errors.Is در برابر sentinel طبیعی‌ترین لایهٔ نگاشت به نوع problem است.
  • context.Context loaderهای هر درخواست و هویت صدازننده را حمل می‌کند؛ هیچ‌چیز سراسری نیست.
  • کد تولیدشده (gqlgen، oapi-codegen) در repo می‌ماند یا در CI تولید می‌شود؛ فایل قرارداد ورودی است و دور شدن build را fail می‌کند.

Laravel ​

Laravel 13 / PHP 8.4. controllerها و resolverها به interface OrderApplication وابسته‌اند (همان use caseهای Service در Go)؛ پیاده‌سازی واقعی پشتش از repository فصل Repositories استفاده می‌کند. هر فایل PHP با php -l بررسی نحوی شده؛ بخش‌های Laravel در برابر مستندات 13.x بازبینی شده‌اند، در یک برنامه اجرا نشده‌اند.

Route، scope و exception ​

abilityهای token در Sanctum نقش scope دارند: مستندات می‌گویند tokenها «may be granted abilities / scopes». alias میدل‌ور abilities باید در bootstrap/app.php ثبت شود، جایی که رندر exception برای Problem Details هم هست (withExceptions با $exceptions->render(...)).

php
<?php

use App\Sales\Http\Controllers\CancellationRequestController;
use App\Sales\Http\Controllers\OrderController;
use Illuminate\Support\Facades\Route;

// Every route needs a Sanctum token; scopes are the token abilities.
Route::middleware(['auth:sanctum', 'throttle:api'])->group(function (): void {
    Route::middleware('abilities:orders:read')->group(function (): void {
        Route::get('/orders', [OrderController::class, 'index']);
        Route::get('/orders/{order}', [OrderController::class, 'show']);
        Route::get('/cancellation-requests/{id}', [CancellationRequestController::class, 'show']);
    });

    Route::middleware('abilities:orders:write')->group(function (): void {
        Route::post('/orders', [OrderController::class, 'store']);
        // Task-based endpoints: each command is a noun the business already uses.
        Route::post('/orders/{order}/lines', [OrderController::class, 'addLine']);
        Route::post('/orders/{order}/placement', [OrderController::class, 'place']);
        Route::post('/orders/{order}/cancellation-requests', [CancellationRequestController::class, 'store']);
    });
});
php
<?php

use App\Sales\Application\SalesException;
use App\Sales\Http\ProblemDetails;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Laravel\Sanctum\Http\Middleware\CheckAbilities;
use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(api: __DIR__ . '/../routes/api.php')
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->alias([
            'abilities' => CheckAbilities::class,
            'ability' => CheckForAnyAbility::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // Every failure on /api becomes application/problem+json (RFC 9457).
        $exceptions->render(fn (SalesException $e, Request $r) => ProblemDetails::fromFailure($e->failure, $r, $e->getMessage()));
        $exceptions->render(fn (ValidationException $e, Request $r) => ProblemDetails::validation($e, $r));
    })
    ->create();
php
<?php

declare(strict_types=1);

namespace App\Sales\Http;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

/** Called from AppServiceProvider::boot(). Quotas per token, with a lower tier for writes. */
final class RateLimiting
{
    public static function register(): void
    {
        RateLimiter::for('api', function (Request $request) {
            $key = $request->user()?->currentAccessToken()?->id ?? $request->ip();

            return $request->isMethodSafe()
                ? Limit::perMinute(600)->by("r:{$key}")
                : Limit::perMinute(60)->by("w:{$key}");
        });
    }
}

Resource، Request و Controller ​

API Resource همان DTO است: OrderResource یک OrderView (نه مدل Eloquent) را به شکل منتشرشده نگاشت می‌کند و ETag را در withResponse می‌افزاید. Form Requestها ورودی را اعتبارسنجی می‌کنند؛ ProblemDetails هم شکست دامنه و هم شکست validation را به‌صورت application/problem+json رندر می‌کند.

php
<?php

declare(strict_types=1);

namespace App\Sales\Http\Resources;

use App\Sales\Application\OrderView;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/** @property OrderView $resource */
final class OrderResource extends JsonResource
{
    public static $wrap = null; // no "data" envelope: the order IS the body

    public function toArray(Request $request): array
    {
        $o = $this->resource;
        $links = ['self' => ['href' => "/orders/{$o->id}"]];
        // Links advertise only the transitions the state machine allows now.
        if ($o->status === 'draft') {
            $links['add-line'] = ['href' => "/orders/{$o->id}/lines", 'method' => 'POST'];
            $links['placement'] = ['href' => "/orders/{$o->id}/placement", 'method' => 'POST'];
        } elseif ($o->status === 'placed') {
            $links['cancellation-requests'] = ['href' => "/orders/{$o->id}/cancellation-requests", 'method' => 'POST'];
        }

        return [
            'id' => $o->id,
            'customerId' => $o->customerId,
            'status' => $o->status,
            'lines' => array_map(fn ($l) => [
                'sku' => $l->sku,
                'quantity' => $l->quantity,
                'unitPrice' => ['amountMinor' => $l->unitPriceMinor, 'currency' => $o->currency],
            ], $o->lines),
            'total' => ['amountMinor' => $o->totalMinor, 'currency' => $o->currency],
            'placedAt' => $o->placedAt?->format(DATE_ATOM),
            '_links' => $links,
        ];
    }

    /** Weak ETag from the aggregate version; used for If-Match / If-None-Match. */
    public function withResponse(Request $request, $response): void
    {
        $response->header('ETag', 'W/"' . $this->resource->version . '"');
    }
}
php
<?php

declare(strict_types=1);

namespace App\Sales\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

final class AddLineRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        // The client sends WHAT it wants; the price comes from Catalog, never from the client.
        return [
            'sku' => ['required', 'string'],
            'quantity' => ['required', 'integer', 'min:1', 'max:50'],
        ];
    }
}
php
<?php

declare(strict_types=1);

namespace App\Sales\Http;

use App\Sales\Application\SalesFailure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

/** Builds RFC 9457 responses. The only place internal failures get public codes. */
final class ProblemDetails
{
    private const BASE = 'https://api.example.com/problems/';

    public static function fromFailure(SalesFailure $failure, Request $request, string $detail = ''): JsonResponse
    {
        [$status, $title] = match ($failure) {
            SalesFailure::NotFound => [404, 'Resource not found'],
            SalesFailure::OrderNotEditable => [409, 'Order is not editable'],
            SalesFailure::OrderEmpty => [422, 'Order has no lines'],
            SalesFailure::StaleVersion => [412, 'The order changed since you read it'],
            SalesFailure::AlreadyCancelled => [409, 'Order cannot be cancelled'],
            SalesFailure::UnknownProduct => [422, 'Your request is invalid'],
        };

        return self::make($request, $failure->value, $title, $status, $detail);
    }

    public static function validation(ValidationException $e, Request $request): JsonResponse
    {
        $errors = [];
        foreach ($e->errors() as $field => $messages) {
            foreach ($messages as $message) {
                $errors[] = ['pointer' => '/' . str_replace('.', '/', $field), 'detail' => $message];
            }
        }

        return self::make($request, 'validation-failed', 'Your request is invalid', 422, '', ['errors' => $errors]);
    }

    public static function make(
        Request $request,
        string $type,
        string $title,
        int $status,
        string $detail = '',
        array $extensions = [],
    ): JsonResponse {
        $body = ['type' => self::BASE . $type, 'title' => $title, 'status' => $status];
        if ($detail !== '') {
            $body['detail'] = $detail;
        }
        $body['instance'] = '/' . ltrim($request->path(), '/');

        return response()->json($body + $extensions, $status, ['Content-Type' => 'application/problem+json']);
    }
}
php
<?php

declare(strict_types=1);

namespace App\Sales\Http\Controllers;

use App\Sales\Application\OrderApplication;
use App\Sales\Application\OrderView;
use App\Sales\Application\SalesException;
use App\Sales\Application\SalesFailure;
use App\Sales\Http\ProblemDetails;
use App\Sales\Http\Requests\AddLineRequest;
use App\Sales\Http\Requests\CreateOrderRequest;
use App\Sales\Http\Resources\OrderResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

final class OrderController
{
    public function __construct(private readonly OrderApplication $orders) {}

    public function store(CreateOrderRequest $request): JsonResponse
    {
        $order = $this->orders->createDraft($request->string('customerId')->value(), $request->string('currency')->value());

        return (new OrderResource($order))->response()->setStatusCode(201)->header('Location', "/orders/{$order->id}");
    }

    public function show(Request $request, string $order): JsonResponse|Response
    {
        $view = $this->owned($request, $order);
        $etag = 'W/"' . $view->version . '"';
        if ($request->header('If-None-Match') === $etag) {
            return response('', 304)->header('ETag', $etag);
        }

        return (new OrderResource($view))->response()->header('Cache-Control', 'private, max-age=0, must-revalidate');
    }

    public function index(Request $request): JsonResponse
    {
        $limit = min(max((int) $request->query('limit', 20), 1), 100);
        $after = $request->query('cursor') ? (int) base64_decode((string) $request->query('cursor'), true) : 0;
        // Tenant isolation: the customer comes from the token, never from the query string.
        $rows = $this->orders->list($request->user()->customer_id, $request->query('status'), $after, $limit + 1);

        $more = count($rows) > $limit;
        $rows = array_slice($rows, 0, $limit);

        return response()->json(array_filter([
            'items' => OrderResource::collection($rows)->resolve($request),
            'nextCursor' => $more ? rtrim(strtr(base64_encode((string) end($rows)->seq), '+/', '-_'), '=') : null,
        ], fn ($v) => $v !== null));
    }

    public function addLine(AddLineRequest $request, string $order): JsonResponse
    {
        $this->owned($request, $order);
        $expected = $this->version($request->header('If-Match'));
        $view = $this->orders->addLine($order, $request->string('sku')->value(), $request->integer('quantity'), $expected);

        return (new OrderResource($view))->response()->setStatusCode(201)
            ->header('Location', "/orders/{$order}/lines/" . $request->string('sku')->value());
    }

    /** Placement moves money: If-Match is mandatory (428 when missing). */
    public function place(Request $request, string $order): JsonResponse
    {
        $this->owned($request, $order);
        $expected = $this->version($request->header('If-Match'));
        if ($expected === 0) {
            return ProblemDetails::make($request, 'precondition-required', 'If-Match header is required', 428);
        }

        return (new OrderResource($this->orders->place($order, $expected)))->response();
    }

    /** 404, not 403: do not reveal that someone else's order exists. */
    private function owned(Request $request, string $id): OrderView
    {
        $view = $this->orders->get($id);
        if ($view->customerId !== $request->user()->customer_id) {
            throw new SalesException(SalesFailure::NotFound);
        }

        return $view;
    }

    private function version(?string $header): int
    {
        return (int) trim(str_replace('W/', '', (string) $header), '" ');
    }
}
php
<?php

declare(strict_types=1);

namespace App\Sales\Http\Controllers;

use App\Sales\Application\OrderApplication;
use App\Sales\Application\SalesException;
use App\Sales\Application\SalesFailure;
use App\Sales\Http\Requests\RequestCancellationRequest;
use App\Sales\Http\Resources\CancellationRequestResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

final class CancellationRequestController
{
    public function __construct(private readonly OrderApplication $orders) {}

    /** 202 Accepted: the request is recorded; Fulfilment decides later. */
    public function store(RequestCancellationRequest $request, string $order): JsonResponse
    {
        $this->assertOwner($request, $order);
        $view = $this->orders->requestCancellation($order, $request->string('reason')->value(), $request->header('Idempotency-Key'));

        return (new CancellationRequestResource($view))->response()->setStatusCode(202)
            ->header('Location', "/cancellation-requests/{$view->id}")
            ->header('Retry-After', '1');
    }

    public function show(Request $request, string $id): JsonResponse
    {
        $view = $this->orders->cancellation($id);
        $this->assertOwner($request, $view->orderId);

        return (new CancellationRequestResource($view))->response();
    }

    private function assertOwner(Request $request, string $orderId): void
    {
        if ($this->orders->get($orderId)->customerId !== $request->user()->customer_id) {
            throw new SalesException(SalesFailure::NotFound);
        }
    }
}

قراردادِ لایهٔ برنامه که controllerها استفاده می‌کنند:

php
<?php

declare(strict_types=1);

namespace App\Sales\Application;

/**
 * The use cases the API may call. Controllers and GraphQL resolvers depend on
 * this interface only; they never touch the aggregate or Eloquent.
 * Every method throws SalesException for a business failure.
 */
interface OrderApplication
{
    public function createDraft(string $customerId, string $currency): OrderView;

    public function get(string $orderId): OrderView;

    /** @return list<OrderView> ordered by creation, strictly after $afterSeq */
    public function list(string $customerId, ?string $status, int $afterSeq, int $limit): array;

    /** $expectedVersion 0 means "do not check". */
    public function addLine(string $orderId, string $sku, int $quantity, int $expectedVersion = 0): OrderView;

    public function place(string $orderId, int $expectedVersion): OrderView;

    /** Replaying the same $idempotencyKey returns the same request. */
    public function requestCancellation(string $orderId, string $reason, ?string $idempotencyKey): CancellationView;

    public function cancellation(string $requestId): CancellationView;
}

GraphQL با Lighthouse ​

Lighthouse با قرارداد نام‌گذاری Query.order را به App\GraphQL\Queries\Order و Mutation.placeOrder را به App\GraphQL\Mutations\PlaceOrder وصل می‌کند و __invoke را صدا می‌زند. directiveها guard، throttle و validation را به schema اضافه می‌کنند.

graphql
"An ISO 8601 date-time such as 2026-11-25T09:30:00Z."
scalar DateTime @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTime")

type Money {
  amountMinor: Int!
  currency: String!
}

enum OrderStatus { DRAFT PLACED CANCELLED }

enum CancellationState { PENDING COMPLETED REJECTED }

"Catalog's product, resolved through a batch loader."
type Product {
  sku: ID!
  name: String!
}

type OrderLine {
  sku: ID!
  quantity: Int!
  unitPrice: Money!
  product: Product! @field(resolver: "App\\GraphQL\\Resolvers\\OrderLineProduct")
}

type Order {
  id: ID!
  customerId: ID!
  status: OrderStatus!
  lines: [OrderLine!]!
  total: Money!
  placedAt: DateTime
  "Bumped on every change; pass it back as expectedVersion."
  version: Int!
}

type OrderEdge { cursor: String! node: Order! }
type PageInfo { hasNextPage: Boolean! endCursor: String }
type OrderConnection { edges: [OrderEdge!]! pageInfo: PageInfo! }

type CancellationRequest {
  id: ID!
  orderId: ID!
  state: CancellationState!
  reason: String!
  detail: String
}

"A business problem the client can show; not a transport error."
type UserError { code: String! message: String! field: String }

type Query {
  order(id: ID!): Order @guard(with: ["sanctum"])
  orders(status: OrderStatus, first: Int = 20, after: String): OrderConnection! @guard(with: ["sanctum"])
  cancellationRequest(id: ID!): CancellationRequest @guard(with: ["sanctum"])
}

input CreateDraftOrderInput { currency: String! @rules(apply: ["size:3"]) }
input AddOrderLineInput {
  orderId: ID!
  sku: ID!
  quantity: Int! @rules(apply: ["min:1", "max:50"])
  expectedVersion: Int
}
input PlaceOrderInput { orderId: ID! expectedVersion: Int! }
input RequestOrderCancellationInput {
  orderId: ID!
  reason: String!
  idempotencyKey: String
}

type CreateDraftOrderPayload { order: Order userErrors: [UserError!]! }
type AddOrderLinePayload { order: Order userErrors: [UserError!]! }
type PlaceOrderPayload { order: Order userErrors: [UserError!]! }
type RequestOrderCancellationPayload { request: CancellationRequest userErrors: [UserError!]! }

type Mutation {
  createDraftOrder(input: CreateDraftOrderInput!): CreateDraftOrderPayload! @guard(with: ["sanctum"]) @throttle(name: "api")
  addOrderLine(input: AddOrderLineInput!): AddOrderLinePayload! @guard(with: ["sanctum"]) @throttle(name: "api")
  placeOrder(input: PlaceOrderInput!): PlaceOrderPayload! @guard(with: ["sanctum"]) @throttle(name: "api")
  requestOrderCancellation(input: RequestOrderCancellationInput!): RequestOrderCancellationPayload! @guard(with: ["sanctum"]) @throttle(name: "api")
}
php
<?php

declare(strict_types=1);

namespace App\GraphQL\Mutations;

use App\GraphQL\Support\Presenter;
use App\Sales\Application\OrderApplication;
use App\Sales\Application\SalesException;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

final class PlaceOrder
{
    public function __construct(private readonly OrderApplication $orders) {}

    public function __invoke(null $root, array $args, GraphQLContext $context): array
    {
        $in = $args['input'];
        try {
            $order = $this->orders->place($in['orderId'], $in['expectedVersion']);
        } catch (SalesException $e) {
            return ['order' => null, 'userErrors' => [Presenter::userError($e)]];
        }

        return ['order' => Presenter::order($order), 'userErrors' => []];
    }
}
php
<?php

declare(strict_types=1);

namespace App\GraphQL\Queries;

use App\GraphQL\Support\Presenter;
use App\Sales\Application\OrderApplication;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

/** Relay-style connection, keyset-backed; the cursor is an opaque base64 sequence number. */
final class Orders
{
    public function __construct(private readonly OrderApplication $orders) {}

    public function __invoke(null $root, array $args, GraphQLContext $context): array
    {
        $first = min(max((int) ($args['first'] ?? 20), 1), 100);
        $after = isset($args['after']) ? (int) base64_decode($args['after'], true) : 0;
        $status = isset($args['status']) ? strtolower($args['status']) : null;

        $rows = $this->orders->list($context->user()->customer_id, $status, $after, $first + 1);
        $hasNext = count($rows) > $first;
        $rows = array_slice($rows, 0, $first);

        $edges = array_map(fn ($o) => ['cursor' => base64_encode((string) $o->seq), 'node' => Presenter::order($o)], $rows);

        return [
            'edges' => $edges,
            'pageInfo' => ['hasNextPage' => $hasNext, 'endCursor' => $edges === [] ? null : end($edges)['cursor']],
        ];
    }
}
php
<?php

declare(strict_types=1);

namespace App\GraphQL\Resolvers;

use App\GraphQL\Loaders\ProductBatchLoader;
use GraphQL\Deferred;
use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Execution\BatchLoader\BatchLoaderRegistry;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

final class OrderLineProduct
{
    /** @param array{sku: string} $line */
    public function __invoke(array $line, array $args, GraphQLContext $context, ResolveInfo $info): Deferred
    {
        // Always returns the same loader for this path in this request.
        $loader = BatchLoaderRegistry::instance(
            $info->path,
            fn (): ProductBatchLoader => app(ProductBatchLoader::class),
        );

        return $loader->load($line['sku']);
    }
}
php
<?php

declare(strict_types=1);

namespace App\GraphQL\Loaders;

use App\Catalog\ProductCatalog;
use GraphQL\Deferred;

/**
 * Collects every SKU requested while one level of the query is resolved,
 * then asks Catalog once. Lighthouse keeps one instance per query path
 * (see BatchLoaderRegistry), and the registry is per request.
 */
final class ProductBatchLoader
{
    /** @var array<string, true> */
    private array $skus = [];

    /** @var array<string, array{sku: string, name: string}>|null */
    private ?array $results = null;

    public function __construct(private readonly ProductCatalog $catalog) {}

    public function load(string $sku): Deferred
    {
        $this->skus[$sku] = true;

        return new Deferred(function () use ($sku): array {
            // Runs after load() was called for every line in the response.
            $this->results ??= $this->catalog->products(array_keys($this->skus));

            return $this->results[$sku] ?? ['sku' => $sku, 'name' => '(unavailable)'];
        });
    }
}

تست‌ها ​

php
<?php

declare(strict_types=1);

namespace Tests\Feature;

use App\Sales\Application\OrderApplication;
use App\Models\User;
use Laravel\Sanctum\Sanctum;
use Tests\Support\InMemoryOrderApplication;
use Tests\TestCase;

final class OrderApiTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();
        $this->app->instance(OrderApplication::class, new InMemoryOrderApplication());
        Sanctum::actingAs(new User(['customer_id' => 'c1']), ['orders:read', 'orders:write']);
    }

    public function test_lifecycle_uses_task_endpoints_and_problem_details(): void
    {
        $created = $this->postJson('/api/orders', ['customerId' => 'c1', 'currency' => 'EUR'])
            ->assertCreated()
            ->assertHeader('Location', '/orders/ord_1')
            ->assertHeader('ETag', 'W/"1"');

        // Business rule: an empty order cannot be placed (422 problem+json, stable type).
        $this->postJson('/api/orders/ord_1/placement', headers: ['If-Match' => 'W/"1"'])
            ->assertStatus(422)
            ->assertHeader('Content-Type', 'application/problem+json')
            ->assertJsonPath('type', 'https://api.example.com/problems/order-empty');

        $this->postJson('/api/orders/ord_1/lines', ['sku' => 'SKU-1', 'quantity' => 2])
            ->assertCreated()
            ->assertJsonPath('total.amountMinor', 2500)
            ->assertJsonPath('_links.placement.method', 'POST');

        $this->postJson('/api/orders/ord_1/placement')->assertStatus(428);
        $this->postJson('/api/orders/ord_1/placement', headers: ['If-Match' => 'W/"1"'])->assertStatus(412);
        $this->postJson('/api/orders/ord_1/placement', headers: ['If-Match' => 'W/"2"'])
            ->assertOk()
            ->assertJsonPath('status', 'placed');

        $this->getJson('/api/orders/ord_1', ['If-None-Match' => 'W/"3"'])->assertStatus(304);
        $this->postJson('/api/orders/ord_1/lines', ['sku' => 'SKU-1', 'quantity' => 1])
            ->assertStatus(409)
            ->assertJsonPath('type', 'https://api.example.com/problems/order-not-editable');
    }

    public function test_cancellation_is_accepted_not_done_and_idempotent(): void
    {
        $this->postJson('/api/orders', ['customerId' => 'c1', 'currency' => 'EUR']);
        $first = $this->postJson('/api/orders/ord_1/cancellation-requests', ['reason' => 'late'], ['Idempotency-Key' => 'k1'])
            ->assertStatus(202)
            ->assertHeader('Retry-After', '1')
            ->assertJsonPath('state', 'pending');

        $again = $this->postJson('/api/orders/ord_1/cancellation-requests', ['reason' => 'late'], ['Idempotency-Key' => 'k1']);
        $this->assertSame($first->headers->get('Location'), $again->headers->get('Location'));
    }

    public function test_validation_failures_list_json_pointers(): void
    {
        $this->postJson('/api/orders', ['currency' => 'EU'])
            ->assertStatus(422)
            ->assertJsonPath('errors.0.pointer', '/customerId')
            ->assertJsonPath('errors.1.pointer', '/currency');
    }

    public function test_someone_elses_order_is_a_404(): void
    {
        $app = $this->app->make(OrderApplication::class);
        $app->createDraft('someone-else', 'EUR');

        $this->getJson('/api/orders/ord_1')->assertNotFound();
    }

    public function test_token_without_write_scope_is_forbidden(): void
    {
        Sanctum::actingAs(new User(['customer_id' => 'c1']), ['orders:read']);

        $this->postJson('/api/orders', ['customerId' => 'c1', 'currency' => 'EUR'])->assertForbidden();
    }
}
php
<?php

declare(strict_types=1);

namespace Tests\Feature;

use App\Catalog\ProductCatalog;
use App\Models\User;
use App\Sales\Application\OrderApplication;
use Laravel\Sanctum\Sanctum;
use Nuwave\Lighthouse\Testing\MakesGraphQLRequests;
use Tests\Support\InMemoryOrderApplication;
use Tests\TestCase;

final class OrderGraphQlTest extends TestCase
{
    use MakesGraphQLRequests;

    public function test_six_product_fields_cost_one_catalog_call(): void
    {
        $catalog = new class implements ProductCatalog {
            public int $calls = 0;

            public function products(array $skus): array
            {
                $this->calls++;

                return array_combine($skus, array_map(fn ($s) => ['sku' => $s, 'name' => "name of {$s}"], $skus));
            }
        };
        $orders = new InMemoryOrderApplication(['SKU-1' => 1250, 'SKU-2' => 900]);
        foreach (range(1, 3) as $i) {
            $o = $orders->createDraft('c1', 'EUR');
            $orders->addLine($o->id, 'SKU-1', 1);
            $orders->addLine($o->id, 'SKU-2', 1);
        }
        $this->app->instance(OrderApplication::class, $orders);
        $this->app->instance(ProductCatalog::class, $catalog);
        Sanctum::actingAs(new User(['customer_id' => 'c1']), ['orders:read']);

        $this->graphQL(/** @lang GraphQL */ '
            { orders(first: 10) { edges { node { lines { product { name } } } } pageInfo { hasNextPage } } }
        ')->assertJsonCount(3, 'data.orders.edges');

        $this->assertSame(1, $catalog->calls);
    }

    public function test_business_failure_is_user_error_data(): void
    {
        $this->app->instance(OrderApplication::class, $orders = new InMemoryOrderApplication());
        $orders->createDraft('c1', 'EUR');
        Sanctum::actingAs(new User(['customer_id' => 'c1']), ['orders:write']);

        $this->graphQL(/** @lang GraphQL */ '
            mutation { placeOrder(input: {orderId: "ord_1", expectedVersion: 1}) { order { id } userErrors { code } } }
        ')->assertJsonPath('data.placeOrder.userErrors.0.code', 'ORDER_EMPTY')
          ->assertJsonMissingPath('errors');
    }
}

زاویهٔ Laravel ​

  • API Resource (JsonResource) لایهٔ DTO آماده است؛ به آن view برنامه بدهید نه model، وگرنه جدول دوباره نشت می‌کند.
  • Form Request پیش از controller اعتبارسنجی و مجوز می‌دهد؛ برای Problem Details، ValidationException را در withExceptions رندر کنید.
  • Sanctum با abilityها scope می‌دهد؛ مالکیت روی هر منبع باز هم کد شماست.
  • Rate limiting همان RateLimiter::for به‌علاوهٔ throttle:name است؛ Lighthouse با @throttle(name: "api") همان limiter نام‌دار را استفاده می‌کند.
  • Lighthouse schema-first است: directiveها بیشتر resolverهای Eloquent را می‌سازند و resolverهای سفارشی کلاس‌های invokable‌اند. برای دادهٔ غیر Eloquent از BatchLoaderRegistry استفاده کنید و GraphQL\Deferred برگردانید.
  • نسخه‌بندی قرارداد شماست: گروه route (/v1)، هدری که middleware می‌خواند، یا هیچ در GraphQL.

راه‌حل مشکلات کلاسیک (Solving the classic problems) ​

مشکلراه‌حلچطورمزیتهزینه یا محدودیت
مدل داخلی نشت و یخ می‌کندDTO / API Resource برای هر شکل منتشرشدهنگاشت در یک جا؛ aggregate هرگز serialize نشودآزادی refactorیک لایهٔ نگاشت برای نگهداری
کلاینت قاعده را دور می‌زندفرمان‌های وظیفه‌محورPOST .../placement متد Order.Place را صدا می‌زندقاعده در یک جا، audit بهترendpoint بیشتر
retry اثر دوم می‌سازدکلید idempotencyیکتایی (order_id, idem_key)؛ پاسخ ذخیره‌شده را برگردانretry امنذخیره‌سازی و انقضا
دو کاربر روی هم می‌نویسندETag + If-Match، 428 روی فرمان‌های حساسversion از aggregateدفاع استاندارد lost-updateکلاینت باید هدر بفرستد
پاسخ هنوز آماده نیست202 + منبع وضعیترکورد CancellationRequest + workerصادقانه، قابل poll، idempotentجریان دومرحله‌ای کلاینت
مدیریت خطا در هر endpoint فرق داردRFC 9457 و یک نگاشت‌گرfromError / ProblemDetailsیک handler خطا در کلاینتفهرست typeها نیاز به حاکمیت دارد
صفحه‌های offset ردیف جا می‌اندازندcursor کلیدی (keyset)seq > $cursor ORDER BY seq LIMIT n+1پایدار، سریعپرش تصادفی به صفحه نیست
تغییر شکننده لازم شداول افزایشی، بعد نسخه با Deprecation/Sunsetقدیم و جدید را اجرا کنید، مصرف را بسنجیدبازنشستگی برنامه‌ریزی‌شدهمدتی دو مسیر کد
قرارداد از کد دور می‌شودقرارداد-اول، lint، بررسی شکستن، تست providerSpectral + oasdiff + Schemathesis در CIدور شدن build را fail می‌کندزمان CI، نگهداری قواعد
N+1 در GraphQLDataloader / eager loadingdataloadgen، BatchLoaderRegistry، @withتعداد فراخوانی ثابت در هر سطحstate هر درخواست
کسی دادهٔ tenant دیگر را می‌خواندبررسی مالکیت، tenant از tokenowned()، claimهای tokenشایع‌ترین حفره را می‌بنددبررسی روی هر مسیر
هزینهٔ GraphQL بی‌حدحد عمق/پیچیدگی، سقف pagination، persisted queryتنظیم سروربار قابل پیش‌بینیبعضی queryها رد می‌شوند
مصرف‌کننده‌ها شکل‌های متفاوت می‌خواهندGraphQL یا BFFschema برای هر context، ترکیب در بالاترendpoint کمترسطح عملیاتی جدید

از CRUD به شکل جدول تا زبان منتشرشده، گام‌به‌گام ​

Timeline: refactoring GET/PATCH /orders (a table gateway) into task-based endpoints
1  freeze      write the current behaviour as an OpenAPI file; add contract tests that pin it
2  add         POST /orders/{id}/placement next to PATCH status; both call Service.Place
3  guard       PATCH status for placed now returns 409 order-not-editable (rule is in the aggregate)
4  announce    mark PATCH status deprecated in the file; add Deprecation header; tell owners via keys
5  measure     gateway analytics: callers of PATCH status per week
6  sunset      add Sunset header; after the date answer 410 with a problem linking the migration guide
7  clean       delete the PATCH route and the status field from the request schema

انتخاب (Choosing) ​

وضعیتتوصیهتکنیک اضافهدلیل
چند مصرف‌کنندهٔ پایدار، پر از فرمان، قاعده مهمREST وظیفه‌محورOpenAPI، ETag/If-Match، Problem Detailsفرمان و کش به HTTP می‌خورد
کلاینت‌های زیاد با نمای متفاوت، موبایل روی لینک کندGraphQL برای خواندن (و mutationهای نازک)dataloader، persisted query، حد پیچیدگیپاسخ با شکل کلاینت
تجمیع چند context برای یک صفحهBFF، در صورت لزوم GraphQL یا federationهر context OHS خودش را نگه می‌داردمالکیت پیش contextها می‌ماند
سرویس به سرویس داخلی، نوع سخت، streaminggRPCProtobuf با بررسی buf breakingفشرده و تایپ‌دار
خبر دادن به شرکا که اتفاقی افتادWebhookامضای HMAC، retry، لاگ تحویلpush بدون poll
یکپارچگی بین contextهایی که باید جدا بمانندرویدادOutbox، schema registryجداسازی زمانی
دادهٔ کاتالوگ عمومی و کش‌پذیرREST + CDNCache-Control، ETag، Varyکش HTTP کار می‌کند
صفحهٔ admin یا تنظیمات، زیردامنهٔ پشتیبانCRUD سادهتولید از روی قراردادارزان از زیرکانه بهتر است
پول، موجودی، هویتوظیفه‌محور + idempotency + شرطیscope برای هر فرمانیک اشتباه گران‌تر از زمان طراحی است
مصرف‌کننده‌های آیندهٔ نامعلوماول زبان منتشرشده، فقط تغییر افزایشیtolerant reader، enum بازمدل را یخ نزنید
GraphQL کجا می‌نشیندکجا نمی‌نشیند
کلاینت و نمای متفاوت زیادیک یا دو مصرف‌کنندهٔ با نیاز ثابت
خواندن‌محور با گراف شیء عمیقسطح پر از فرمان و گردش‌کارمحور
تکرار سریع در فرانت‌اندنیاز سنگین به کش HTTP و CDN
تیم BFF یا router که مالکش می‌شودظرفیتی برای اداره کردن حد query و ابزار نیست
contextهای تایپ‌داری که قابل ترکیب‌اندCRUD ساده روی چند جدول

در معماری: از یک process تا سیستم توزیع‌شده ​

مونولیت: یک process، یک دیتابیس ​

یک برنامهٔ Laravel (یا یک باینری Go): route، controller، application service، aggregate و یک دیتابیس. زبان منتشرشده باز هم وجود دارد: OrderResource و OrderView لایهٔ DTO‌اند، sales.openapi.yaml قرارداد است و controller هرگز return $order نمی‌کند. REST و GraphQL دو نقطهٔ ورود‌اند که همان Service را صدا می‌زنند، همان‌طور که cmd/server/main.go نشان می‌دهد. مثال روزمره: اپ وب و موبایل خود فروشگاه /orders و /graphql را روی یک میزبان صدا می‌زنند. ساده‌ترین استفادهٔ درست: endpointهای وظیفه‌محور، ETag روی خواندن، Problem Details، keyset pagination و یک contract test برای هر قاعده.

مونولیت ماژولار و چند دیتابیس ​

هر ماژول (Sales، Fulfilment، Billing، Catalog، Identity) یک interface عمومی و DTO دارد: همان Open Host Service و Published Language درون‌process (Modular Monolith). Billing OrderApplication::get() را صدا می‌زند و OrderView می‌گیرد، هرگز entityهای Sales را. API روی HTTP لایهٔ نازکی است که interfaceهای ماژول‌ها را ترکیب می‌کند؛ با چند دیتابیس، هر ماژول schema خودش را دارد و API هرگز بینشان join نمی‌زند (Data Ownership). قرارداد درون‌process با تست معماری بررسی می‌شود (deptrac در PHP، قاعدهٔ import و پکیج‌های internal در Go). روزی که یک ماژول بیرون کشیده شود interfaceش به قرارداد HTTP یا gRPC با همان شکل‌ها تبدیل می‌شود.

میکروسرویس: یک OHS برای هر سرویس ​

Sales، Fulfilment و Billing هرکدام API و رویدادهای خودشان را منتشر می‌کنند؛ هر API فایل OpenAPI، scopeها و سیاست نسخه‌بندی خودش را دارد. Billing یا downstream conformist زبان Sales است، یا جایی که واژه‌های Sales نمی‌خواند یک anticorruption layer می‌سازد (Context Maps). gateway کلید، سهمیه و مسیریابی را اداره می‌کند؛ BFF وب Order را از Sales و Product را از Catalog تجمیع می‌کند.

Timeline: customer cancels a placed order (three services, one saga; see /messaging/saga-pattern)
1  web BFF   POST sales/orders/o1/cancellation-requests (Idempotency-Key k1)       -> 202 can_1
2  sales     tx: insert can_1(pending) + outbox row OrderCancellationRequested
3  relay     publishes OrderCancellationRequested
4  fulfilment consumes (inbox dedupe), releases picks -> publishes StockReleased | ReleaseRefused
5  billing   consumes StockReleased -> refunds -> publishes RefundIssued
6  sales     consumes RefundIssued -> order.Cancel(); can_1 = completed
7  web BFF   GET sales/cancellation-requests/can_1 (poll) or receives webhook sales.order.cancelled.v1

کلاینت یک 202 و یک منبع وضعیت می‌بیند؛ saga، outbox و inboxها پشت آن می‌مانند (Saga، Outbox، Inbox).

نمونه‌های production. (1) مستندات API در Stripe نمونهٔ عمومی idempotency به‌عنوان بخشی از قرارداد است: کلید idempotency روی POST و «retries with the same key return the saved response». (2) Zalando راهنمای API خود را با «API First» به‌عنوان یک اصل منتشر کرده و راهنمایش Problem JSON (RFC 9457) و هدر اختیاری Idempotency-Key را نام می‌برد. (3) Apollo federation را راه ترکیب subgraphهای تیم‌های مختلف در یک supergraph مستند کرده. اینها حقایقِ مستندِ همان منابع‌اند؛ اینکه هر شرکت درونش چطور اعمال می‌کند ادعا نشده.

داده توزیع‌شده: replica، کش و چند region ​

کجا می‌شکندکلاینت چه می‌بینددفاع در API
تأخیر replica خواندنPOST /orders می‌دهد 201، بعد GET /orders/o1 می‌دهد 404representation کامل را از خود فرمان برگردانید؛ خواندنِ بعد از نوشتن را برای مدتی کوتاه به primary بفرستید؛ یا توکن «بعد از فلان موقعیت» را در هدر حمل کنید
کش HTTP/CDNسفارش ثبت‌شده هنوز پیش‌نویس نشان داده می‌شودCache-Control: private, max-age=0, must-revalidate به‌علاوهٔ ETag؛ روی کش مشترک Vary: Authorization؛ دادهٔ شخصی هرگز عمومی کش نشود
کش کلاینت GraphQLدو نما از یک سفارش با هم نمی‌خوانندid سراسری، order در payload mutation را دوباره بگیرید، version سازگار
نوشتن چند regionفرمان تکراری در دو regionهر aggregate به یک region خانه برود؛ کلید idempotency در ذخیره‌ای که هر دو ببینند
retry و بی‌نظمی webhookگیرنده sales.order.cancelled.v1 را دوبار، یا پیش از sales.order.placed.v1 می‌بیندid رویداد، timestamp، ترتیب، گیرندهٔ idempotent
دید نهایی‌سازگار بین contextهاسفارش placed می‌گوید، Billing unpaidدر API نامش را ببرید (paymentStatus با تأخیر مستند)، یا پشت منبع وضعیت پنهانش کنید

سازوکار ردیف اول در Replication, Read Replicas & Failover و replication سمت خواندن در Data Patterns است.

مسیر مقیاس: 1x، 10x، 100x ​

بارطراحیچه چیزی عوض می‌شود
1x: یک تیم، چند کلاینتREST یا GraphQL در مونولیت، فایل قرارداد در repolint و بررسی شکستن در CI
10x: کلاینت و شریک زیادgateway با کلید و سهمیه، پورتال توسعه‌دهنده، درخواست شرطی، CDN برای خواندن عمومیanalytics به ازای هر کلید؛ سیاست deprecation؛ webhook با لاگ تحویل
100x: تیم و context زیادOHS برای هر context، BFF برای هر نوع کلاینت، federation یا router، schema registry و بررسی قرارداد، gatewayهای منطقه‌ایحاکمیت: مالک برای هر type، بازبینی هر تغییر، SLO برای هر operation، حد هزینهٔ query

آزمایشگاه: Sales را دو بار منتشر کنید ​

دستورها یک process Go روی میزبان را اجرا می‌کنند: بدون Docker، بدون دیتابیس. خروجی زیر از اجرای واقعی cmd/server با ADDR=127.0.0.1:18080 گرفته شده (idها تصادفی‌اند؛ مال شما فرق دارد). گام‌های Laravel و ابزار (7 تا 9) expected، not run هستند.

# 0  from docs/snippets/ddd/api-realization-rest-graphql/go
go vet ./... && go test ./...
# expected: ok  academy/api-realization-rest-graphql/graph, ok  .../rest

ADDR=127.0.0.1:18080 go run ./cmd/server &
B=http://127.0.0.1:18080

# 1  create a draft: 201, Location and a weak ETag
curl -si -X POST $B/orders -d '{"customerId":"c1","currency":"EUR"}'
#  HTTP/1.1 201 Created
#  Etag: W/"1"
#  Location: /orders/ord_040ed068dc188bad
#  {"id":"ord_040e...","status":"draft","lines":[],"total":{"amountMinor":0,"currency":"EUR"},
#   "_links":{"add-line":{...},"placement":{...},"self":{...}}}

ID=ord_040ed068dc188bad   # use the id you got

# 2  add a line: price comes from Catalog; the version moves to 2
curl -si -X POST $B/orders/$ID/lines -d '{"sku":"SKU-1","quantity":2}'
#  HTTP/1.1 201 Created   Etag: W/"2"   Location: /orders/ord_040e.../lines/SKU-1

# 3  place without the precondition, then with a stale one
curl -si -X POST $B/orders/$ID/placement
#  HTTP/1.1 428 Precondition Required
#  {"type":"https://api.example.com/problems/precondition-required","title":"If-Match header is required","status":428,...}
curl -si -X POST -H 'If-Match: W/"1"' $B/orders/$ID/placement
#  HTTP/1.1 412 Precondition Failed
#  {"type":".../problems/stale-representation","title":"The order changed since you read it","status":412,
#   "detail":"Re-read the order and retry with the new ETag.",...}

# 4  place with the fresh tag
curl -si -X POST -H 'If-Match: W/"2"' $B/orders/$ID/placement
#  HTTP/1.1 200 OK   Etag: W/"3"

# 5  ask to cancel: 202 now, the worker finishes within about two seconds
curl -si -X POST -H 'Idempotency-Key: k1' $B/orders/$ID/cancellation-requests -d '{"reason":"changed my mind"}'
#  HTTP/1.1 202 Accepted
#  Location: /cancellation-requests/can_bf1e710e676cb50f
#  Retry-After: 1
#  {"id":"can_bf1e...","orderId":"ord_040e...","state":"pending","reason":"changed my mind",...}
# repeat with the same key: the same can_... is returned (replay, no second request)
# poll: GET $B/cancellation-requests/can_...  -> "state":"pending", later "completed"

# 6  the same use cases through GraphQL
curl -s $B/graphql -H 'Content-Type: application/json' \
  -d '{"query":"{ order(id:\"'$ID'\") { status version lines { product { name } } } }"}'
#  {"data":{"order":{"status":"CANCELLED","version":4,"lines":[{"product":{"name":"Mug"}}]}}}
curl -s $B/graphql -H 'Content-Type: application/json' \
  -d '{"query":"mutation { placeOrder(input:{orderId:\"'$ID'\", expectedVersion:1}) { order { id } userErrors { code message } } }"}'
#  {"data":{"placeOrder":{"order":null,"userErrors":[{"code":"STALE_VERSION","message":"order changed since you read it"}]}}}

# 7  (expected, not run) Laravel: php artisan test --filter=OrderApiTest
#    the five tests in OrderApiTest.php pass with the in-memory OrderApplication
# 8  (expected, not run) lint the contract
#    npx @stoplight/spectral-cli lint openapi/sales.openapi.yaml --ruleset openapi/.spectral.yaml
#    expected: no errors; delete the 'security' of one POST and the sales-commands-need-security rule fails
# 9  (expected, not run) breaking-change check
#    oasdiff breaking old.yaml openapi/sales.openapi.yaml
#    expected: adding a new required property to CreateOrder is reported as breaking; adding an optional one is not

چه چیزی را ببینید: گام 3 دو پیش‌شرط را با statusهای متفاوت (428 و 412) و typeهای پایدار رد می‌کند؛ گام 5 پیش از تمام شدن کار برمی‌گردد؛ گام 6 نشان می‌دهد شکست کسب‌وکاری در GraphQL یک 200 با داده است، در حالی که معادلش در REST 412 است. سرور یک process با ذخیرهٔ درحافظه است، پس تأخیر replica‌ای برای دیدن نیست: آن بخش از داده توزیع‌شده توضیح داده شده، اجرا نشده.

بدفهمی‌های رایج (Common misconceptions) ​

باورواقعیت
REST یعنی CRUD روی جدولمنبع هر چیز نام‌پذیر است؛ placement و cancellation-requests منبع‌اند
API باید آینهٔ aggregate باشدآینهٔ زبان منتشرشده است که کوچک‌تر و پایدارتر است
PATCH status راه RESTful تغییر وضعیت استنیت کسب‌وکار را پنهان می‌کند و کلاینت را از قاعده فراری می‌دهد؛ فرمان به‌صورت اسم قاعده را در aggregate نگه می‌دارد
POST همیشه برای retry امن استبه‌طور پیش‌فرض idempotent نیست؛ Idempotency-Key اضافه کنید
200 برای هر چیز موفق خوب است201، 202، 204، 304 معنایی دارند که کش و کلاینت به آن عمل می‌کنند
type خطا فقط متن استکلید ماشینی است؛ پیام می‌تواند عوض شود، type نه
hypermedia سطح 3 اجباری استوقتی فرمان‌های مجاز به وضعیت بستگی دارند یا کلاینت ناشناس است می‌ارزد؛ وگرنه سطح 2 کافی است
/v2/ نسخه‌بندی را حل می‌کندتغییر افزایشی و برنامهٔ بازنشستگی حل می‌کند؛ URL فقط برچسب است
GraphQL نسخه ندارد، پس چیزی نمی‌شکندحذف یا تغییر نوع field کلاینت را می‌شکند؛ از @deprecated و analytics مصرف استفاده کنید
خطای GraphQL همیشه در errors می‌رودنتیجهٔ کسب‌وکاری به payload (userErrors) می‌رود؛ errors برای شکست خودِ درخواست است
dataloader N+1 را همه‌جا حل می‌کندفقط داخل یک سطح از یک درخواست دسته می‌کند؛ حد، کش و queryی batch خوب هنوز لازم است
gateway سرویس را امن می‌کندهویت را ثابت و سیاست درشت را اعمال می‌کند؛ مجوز روی هر منبع کار سرویس است
فایل OpenAPIِ تولیدشده همان قرارداد استفقط فایل بازبینی‌شده، lintشده و break-check‌شده قرارداد است
Federation به همه یک مدل مشترک می‌دهدمدل‌هایی را ترکیب می‌کند که هر context هنوز مالکشان است
Webhook فقط یک POST استامضا، retry، id، قاعدهٔ ترتیب و لاگ تحویل می‌خواهد

چکیده (Cheat sheet) ​

موضوعچه چیزی را یادتان بماند
API در زبان DDDOpen Host Service به‌علاوهٔ Published Language یک context
چه چیزی را نشان بدهیمآنچه مصرف‌کننده لازم دارد و می‌توانید به قولش پایبند بمانید؛ نه aggregate
Resourceهر چیز نام‌پذیر؛ یک aggregate می‌تواند چند منبع باشد
فرماناسم برای قصد: /placement، /cancellation-requests، هرگز PATCH status
متدهاGET safe؛ PUT/DELETE idempotent؛ POST کلید می‌خواهد
همزمانیETag روی خواندن، If-Match روی فرمان، 412 کهنه، 428 الزامی
خطاهاRFC 9457، type پایدار، errors[].pointer برای validation
ناهمگام202 + Location + Retry-After + منبع وضعیت
Paginationcursor کلیدی، مات، limit + 1 تا بفهمید صفحهٔ بعد هست
نسخه‌بندیاضافه کنید، عوض نکنید؛ Deprecation بعد Sunset؛ مصرف‌کننده‌ها را ردیابی کنید
قرارداداول OpenAPI؛ lint با Spectral؛ بررسی شکستن؛ تست provider
API managementgateway برای کلید، سهمیه، مسیریابی، analytics؛ context برای قاعده و مالکیت
GraphQLschema از مدل منتشرشده؛ input + payload + userErrors؛ connection
N+1dataloader برای هر درخواست؛ نتیجه به ترتیب کلید؛ خطا برای هر کلید
امنیتهویت، scope، مالکیت، rate limit؛ tenant از token؛ 404 نه 403
تستتست handler، lint قرارداد، بررسی شکستن، راستی‌آزمایی provider، consumer-driven contract

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — در زبان DDD، Open Host Service و Published Language چیست و با فایل OpenAPI شما چه نسبتی دارد؟ مهم ​

پاسخ

پاسخ: OHS پروتکل بازی است که context به همهٔ مصرف‌کننده‌ها می‌دهد؛ Published Language مدل مستندشدهٔ آن پروتکل است، جدا از مدل داخلی. فایل OpenAPI (و SDL در GraphQL و schemaی رویدادها) شکل مکتوب زبان منتشرشده است.

۲ — چرا json.Marshal(order) در handler اشتباه طراحی است حتی وقتی JSON درست به نظر می‌رسد؟ حیاتی ​

پاسخ

پاسخ: فیلدهای aggregate را منتشر می‌کند، پس هر refactor تغییری شکننده می‌شود و داده‌ٔ خصوصی ممکن است نشت کند. Evans: مدل داخلی که برای تبادل استفاده شود «essentially becomes frozen». برای هر شکل منتشرشده یک DTO بسازید.

۳ — دو دلیل برای ترجیح POST /orders/{id}/placement بر PATCH /orders/{id} با فیلد status بیاورید. مهم ​

پاسخ

پاسخ: قاعده در aggregate پشت یک فرمان نام‌دار می‌ماند (کلاینت نمی‌تواند stateها را دور بزند)؛ audit و مجوز (orders:write برای هر فرمان) به زبان کسب‌وکار حرف می‌زنند؛ فرمان جدید کلاینت‌های قدیمی را نمی‌شکند.

۴ — POST یک کلاینت timeout می‌خورد و retry می‌کند. چطور از درخواست لغوِ دوم جلوگیری می‌کنید؟ حیاتی ​

پاسخ

پاسخ: Idempotency-Key که با قید یکتا ذخیره می‌شود؛ retry کلید را پیدا می‌کند و همان 202 و Location اصلی را برمی‌گرداند.

۵ — ETag، If-Match، 412 و 428 چه می‌دهند و در aggregate به چه چیزی نگاشت می‌شوند؟ مهم ​

پاسخ

پاسخ: دفاع در برابر lost update روی HTTP. ETag همان version aggregate را حمل می‌کند؛ If-Match فرمان را شرطی می‌کند؛ 412 یعنی نسخه کهنه بود؛ 428 یعنی سرور هدر را الزامی کرده. compare-and-set روی version در repository همان ایده است.

۶ — کِی 202 Accepted برمی‌گردانید و پاسخ باید چه داشته باشد؟ حیاتی ​

پاسخ

پاسخ: وقتی کار بعداً تمام می‌شود (Fulfilment باید موجودی را آزاد کند). باید Location به منبع وضعیت، وضعیت فعلی در بدنه و ترجیحاً Retry-After داشته باشد. کلاینت poll می‌کند یا webhook می‌گیرد.

۷ — چرا cursor کلیدی از ?page=7 بهتر است و limit + 1 چه می‌کند؟ مهم ​

پاسخ

پاسخ: offset زیر insertهای همزمان ردیف جا می‌اندازد یا تکرار می‌کند و با offset بزرگ کند می‌شود؛ keyset پایدار و سازگار با index است. یک ردیف اضافه گرفتن بدون query شمارش نشان می‌دهد صفحهٔ بعد هست.

۸ — سه تغییر افزایشی و سه تغییر شکننده نام ببرید. حیاتی ​

پاسخ

پاسخ: افزایشی: فیلد اختیاری جدید در پاسخ، endpoint جدید، فیلد اختیاری جدید در درخواست. شکننده: حذف یا تغییر نام فیلد، سخت‌تر کردن validation، فیلد اجباری جدید در درخواست (و تغییر معنای فیلد).

۹ — در GraphQL «سفارش قبلاً ثبت شده» را کجا گزارش می‌کنید و چرا؟ مهم ​

پاسخ

پاسخ: در payload mutation به‌صورت userErrors { code message } با HTTP 200، چون نتیجهٔ عادی کسب‌وکاری است که UI باید نشان بدهد. آرایهٔ errors سطح بالا برای شکست خودِ درخواست است.

۱۰ — شش field OrderLine.product در یک query خواسته شده. چند فراخوانی Catalog باید رخ دهد و چه چیزی آن را ممکن می‌کند؟ مهم ​

پاسخ

پاسخ: یک. یک dataloader برای هر درخواست کلیدها را جمع می‌کند و Catalog.Products را یک بار صدا می‌زند (dataloadgen در Go؛ BatchLoaderRegistry با Deferred در Lighthouse). loader باید برای هر درخواست باشد و نتیجه را به ترتیب کلید بدهد.

۱۱ — API gateway چه چیزی را می‌تواند اعمال کند و چه چیزی را سرویس Sales باید خودش بررسی کند؟ حیاتی ​

پاسخ

پاسخ: Gateway: کلید، اعتبار token، scope درشت، سهمیه، مسیریابی، analytics. سرویس: اینکه این سفارش مال این مشتری است، invariantهای aggregate، idempotency و معنای خطا.

۱۲ — کدام تست‌ها شکستن قول به مصرف‌کننده را build-fail می‌کنند؟ مهم ​

پاسخ

پاسخ: lint قرارداد با Spectral، diff شکستن در برابر قرارداد منتشرشده، راستی‌آزمایی سرور در حال اجرا با فایل، و consumer-driven contractها.

واژه‌نامه (Glossary) ​

اصطلاحمعنا
«سرویس میزبان باز (Open Host Service, OHS)»context یک پروتکل باز به همهٔ مصرف‌کننده‌ها می‌دهد، نه مترجم برای هرکدام
«زبان منتشرشده (Published Language, PL)»مدل تبادلِ مستند و مشترک آن پروتکل، جدا از مدل داخلی
«API»رابط زمان اجرایی که نرم‌افزار دیگر با آن از context استفاده می‌کند
«منبع (Resource)»اطلاعاتِ نام‌پذیر با شناسه (URI)
«نمایش (Representation)»بایت‌هایی که وضعیت یک منبع را در یک لحظه و یک media type نشان می‌دهند
«اگریگیت (Aggregate)»مرز سازگاری در مدل دامنه که ریشه‌اش از آن محافظت می‌کند
«DTO»شیء انتقال داده: شکلی برای سیم، نه برای دامنه
«API Resource در Laravel»کلاس JsonResource که داده را به شکل JSON منتشرشده نگاشت می‌کند
«API وظیفه‌محور (Task-based API)»endpointهایی به نام فرمان کسب‌وکار نه به‌روزرسانی فیلد
«CRUD»ساخت، خواندن، به‌روزرسانی، حذف روی داده بدون فرمان دامنه
«فرمان (Command)»درخواست تغییر وضعیت که به‌صورت یک قصد نام‌گذاری شده
Safe methodمتدی که وضعیت را عوض نمی‌کند (GET، HEAD)
«ایدمپوتنت (Idempotent)»تکرار اثری برابر یک بار دارد
Idempotency-Keyکلید انتخاب کلاینت که سرور با آن retry یک POST را می‌شناسد
Status codeکلاس و معنای نتیجهٔ HTTP (201، 202، 409، 412، 422، 428، 429)
ETagvalidator یک representation؛ اینجا version aggregate به‌صورت برچسب ضعیف
If-Matchهدر درخواست که فرمان را به ETag فعلی مشروط می‌کند
If-None-Matchهدر revalidation؛ اگر تغییر نکرده باشد 304
412 Precondition Failedشرط (If-Match) برقرار نبود
428 Precondition Requiredسرور درخواست شرطی را الزامی کرده
202 Acceptedدریافت شد، هنوز پردازش نشده
Locationهدر اشاره به منبع ساخته‌شده یا منبع پایش
Retry-Afterهدری که می‌گوید کلاینت کِی دوباره تلاش کند
«جزئیات مسئله (Problem Details)»قالب خطا در RFC 9457، application/problem+json
Problem typeURI پایداری که نوع خطا را نام می‌برد
JSON Pointerمسیر درون سند JSON، در errors[].pointer
HATEOAShypermedia به‌عنوان موتور وضعیت برنامه
Richardson Maturity Modelچهار سطح Fowler: تونل، منبع، فعل، hypermedia
HALقرارداد hypermedia در JSON با _links و _embedded
JSON:APIspecification برای شیء منبع، رابطه، include و paging
«صفحه‌بندی کلیدی (Keyset pagination)»صفحه‌بندی با «بعد از این کلید» به‌جای offset
Opaque cursorنشانگری که کلاینت نباید قالبش را تجزیه کند
Link headerهدر RFC 8288 برای rel="next" و روابط دیگر
Tolerant readerکلاینتی که فیلد و مقدار ناشناس را نادیده می‌گیرد
Deprecation headerاعلام می‌کند API یا نسخه دیگر توصیه نمی‌شود
Sunset headerهدر RFC 8594 با تاریخی که URI احتمالاً پاسخ‌گو نخواهد بود
«قرارداد-اول (Contract-first)»نوشتن و بازبینی توصیف API پیش از کد
OpenAPIspecification توصیف APIهای HTTP (اینجا 3.1.0)
Spectrallinter که ruleset روی فایل OpenAPI و AsyncAPI اعمال می‌کند
oasdiffابزار مقایسهٔ فایل‌های OpenAPI و گزارش تغییر شکننده
«قرارداد مصرف‌کننده‌محور (Consumer-driven contract)»مصرف‌کننده‌ها می‌گویند چه استفاده می‌کنند؛ provider باید برآورده کند (Pact)
API gatewayreverse proxy جلوی APIها که سیاست اعمال می‌کند (Kong، Apigee)
KongAPI gateway با plugin و پورتال توسعه‌دهنده
Apigeeپلتفرم API management در Google Cloud
Developer portalسایتی که مصرف‌کننده‌ها مستندات می‌خوانند و کلید می‌گیرند
Quota / rate limitسقف فراخوانی برای هر کلید و بازه؛ عبور = 429
Sanctumبستهٔ احراز هویت token و SPA در Laravel؛ tokenها ability دارند
Scope / abilityمجوز نام‌دار روی token (orders:write)
«جداسازی tenant (Tenant isolation)»اطمینان از اینکه صدازننده فقط به دادهٔ خودش می‌رسد
BOLAbroken object-level authorization: خواندن شیء دیگران با id
GraphQLزبان query و runtime تایپ‌دار برای API
SDLزبان تعریف schema در GraphQL
Resolverتابعی که مقدار یک field را می‌سازد
Input typeنوع GraphQL برای آرگومان
Payload typeنوع بازگشتی mutation که نتیجه و userErrors دارد
userErrorsفیلد payload که شکست‌های کسب‌وکاری را به‌صورت داده حمل می‌کند
Relay connectionالگوی pagination با edges، node، cursor، pageInfo
«مسئلهٔ N+1 (N+1 problem)»یک query برای فهرست و بعد یکی برای هر آیتم
Dataloaderدسته‌کننده و کش کلیدی برای هر درخواست
Lighthouseبستهٔ GraphQL schema-first برای Laravel
gqlgenتولیدکنندهٔ کد GraphQL schema-first برای Go
Federationترکیب subgraphهای تیم‌های مختلف در یک supergraph
Supergraphگراف واحد ترکیب‌شدهٔ federation
Schema stitchingادغام schemaهای راه‌دور در gateway با لینک صریح
BFFBackend for Frontend: API در مالکیت یک نوع کلاینت
gRPCچارچوب RPC تایپ‌دار روی HTTP/2 با قرارداد Protobuf
Webhookcallback HTTP که API به URL مصرف‌کننده می‌فرستد
امضای HMACهش کلیددار که ثابت می‌کند webhook از فرستنده است
AsyncAPIspecification شبیه OpenAPI برای APIهای رویدادمحور
Outboxذخیرهٔ رویداد در همان تراکنش و تحویل بعدی با relay

منابع (References) ​

همه با curl گرفته و ذخیره شده‌اند در /private/tmp/claude-501/-Users-m-negahi-Projects-academy/da531b0a-541e-4005-be7e-84d5726fa12b/scratchpad/sources/api-realization-rest-graphql/، status 200 مگر ذکر شود.

ساخته‌شده توسط Morteza Negahi