API Development Architect
Designs a production-ready RESTful API with OpenAPI spec, secure auth, validation, and scalable architecture.
Example run
Generated by Claude Opus 5.5 on November 24, 2026
Inputs used
- API name
- GearLoop API
- Business domain
- Peer-to-peer outdoor gear rental marketplace (tents, kayaks, climbing gear, bikes) connecting individual gear owners with renters
- Resource list
- - **User**: id, email, password_hash (nullable if OAuth-only), full_name, role (renter | owner | admin), phone, is_verified, stripe_connect_account_id (for owners), created_at, updated_at. One user can own many Listings, make many Bookings, write many Reviews. - **Listing**: id, owner_id (FK -> User), category_id (FK -> Category), title, description, daily_price_cents, currency, condition (new | good | fair), location (lat/lng + city/region), deposit_cents, cancellation_policy (flexible | moderate | strict), status (draft | published | paused | archived), photos (array of URLs), created_at, updated_at. Belongs to one owner and one category; has many AvailabilitySlots, Bookings, Reviews. - **Category**: id, name, slug, parent_category_id (nullable, for subcategories like "Camping > Tents"), icon_url. Self-referential tree; has many Listings. - **AvailabilitySlot**: id, listing_id (FK), start_date, end_date, is_blocked (owner manually blocked) or is_booked. Used to compute real-time availability calendar for a Listing. - **Booking**: id, listing_id (FK), renter_id (FK -> User), owner_id (denormalized FK -> User), start_date, end_date, status (pending | confirmed | active | completed | cancelled | disputed), total_price_cents, deposit_cents, service_fee_cents, payment_id (FK -> Payment), cancellation_reason (nullable), created_at, updated_at. Belongs to one Listing and one renter; has one Payment, may have one Review from each side (renter->owner, owner->renter). - **Payment**: id, booking_id (FK), stripe_payment_intent_id, amount_cents, currency, status (requires_action | authorized | captured | refunded | partially_refunded | failed), payout_id (nullable FK -> Payout), idempotency_key, created_at. - **Payout**: id, owner_id (FK -> User), stripe_transfer_id, amount_cents, currency, status (pending | paid | failed), period_start, period_end, created_at. Aggregates multiple completed Payments for an owner. - **Review**: id, booking_id (FK), author_id (FK -> User), target_id (FK -> User or Listing), rating (1-5), comment, created_at. One review per party per completed booking. - **Conversation** and **Message**: Conversation has id, listing_id (nullable), participant_ids (renter + owner), created_at; Message has id, conversation_id (FK), sender_id (FK), body, read_at, created_at. Supports pre-booking Q&A threads tied to a Listing.
- Language and framework
- Node.js 20 with NestJS 10 (TypeScript, TypeORM)
- Database
- PostgreSQL 15 (with PostGIS extension for location search)
- Authentication method
- OAuth 2.0 / OpenID Connect via Auth0, short-lived JWT access tokens (15 min) + rotating refresh tokens, role-based scopes (renter, owner, admin)
- Expected traffic / scale
- ~50,000 monthly active users, ~500,000 active listings, average 150 req/s sustained with bursts to 800 req/s during summer camping season (June-August) and holiday weekends
GearLoop API: Production Design (v1)
Assumptions
None of the ambiguities block the design, so I've made these calls. Each one is easy to reverse.
| # | Assumption | Why |
|---|---|---|
| A1 | Auth0 owns credentials. The local users table stores auth0_sub and drops password_hash. The API is a pure OAuth2 resource server. It never issues tokens and never sees refresh tokens. |
Avoids storing a second copy of credentials. Refresh-token rotation and reuse detection are Auth0 tenant features. |
| A2 | role becomes roles[]. Every user is a renter. owner is added when they start Stripe Connect onboarding, and admin is granted manually. |
Many owners also rent gear. A single enum would force two accounts. |
| A3 | is_blocked / is_booked become kind: blocked | booked on availability_slots. Every occupied range for a listing, whether an owner block or a booking hold, lives in that one table, and a Postgres exclusion constraint guarantees no overlap. |
This makes double-booking impossible at the database level, even under the 800 req/s burst. |
| A4 | Dates are YYYY-MM-DD in the listing's timezone, as half-open ranges [start_date, end_date). end_date is the return day. Rental days = end - start. |
Removes off-by-one and timezone ambiguity. The timezone is derived from the location when the listing is saved. |
| A5 | Conversations are always two-party. participant_ids is modelled as renter_id + owner_id. |
Lets the database enforce one thread per (listing, renter, owner). |
| A6 | Payments use Stripe Connect "separate charges & transfers". The rental is authorized at request time and captured when the owner confirms. The deposit is a second manual-capture PaymentIntent created about 24h before pickup, because card authorizations expire after about 7 days. payments.kind is either rental or deposit. |
Fits the Payout aggregation model. Captured rental funds are transferred to owners in batches. |
| A7 | Reviews: the renter reviews the listing (which rolls up to the owner), and the owner reviews the renter. Reviews are double-blind: each becomes visible when both parties have submitted or after 14 days. | Industry norm. Prevents retaliatory reviews. |
| A8 | Money is integer minor units (*_cents) plus ISO-4217 currency, fixed per owner's Connect account. The JSON wire format is snake_case. |
Avoids floating-point rounding. Matches the domain model. |
1. Architecture Summary
Mobile/Web ──(PKCE / BFF)──► Auth0 ──► JWT (RS256, 15 min, permissions[])
│
▼
CDN / WAF (Cloudflare or CloudFront + AWS WAF): TLS, edge rate limits, bot rules, cached public GETs
│
▼
ALB ──► NestJS 10 pods (stateless, 4–8 replicas, HPA on CPU + p95 latency)
├─ Guards: JwtAuthGuard → ScopesGuard → UserThrottlerGuard (Redis)
├─ Interceptors: Idempotency (Redis), logging (pino + request_id)
├─ Filter: RFC 7807 Problem Details
├─ Modules: Users · Categories · Listings · Availability · Bookings
│ Payments · Payouts · Reviews · Messaging · Admin · Webhooks
└─ Outbox relay → BullMQ workers (capture/refund, payouts, emails, expiry jobs)
│ │ │
▼ ▼ ▼
PgBouncer (txn mode) Redis (cache, rate limit, Stripe (Connect, PaymentIntents, webhooks)
│ idempotency, BullMQ) S3 + image CDN (presigned uploads)
▼
PostgreSQL 15 + PostGIS: primary (writes, read-your-writes) + 1–2 read replicas (search, public reads)
Key design decisions
- Correctness lives in the database. The exclusion constraint prevents overlapping bookings. A compare-and-set
UPDATE … WHERE status = :fromprevents race conditions in booking state changes. Unique indexes enforce one review per party and one conversation per pair. - State changes are explicit action endpoints (
POST /bookings/{id}/confirm), notPATCH status. Each action has its own authorization rule, audit record and side effects. Every booking response includesallowed_actions, so clients don't have to re-implement the state machine. - No network calls inside DB transactions. Stripe calls happen after commit, using deterministic Stripe idempotency keys. Follow-up side effects go through a transactional outbox, so a crash never leaves a captured payment without its matching booking state.
- Authorization has two layers. Coarse scopes come from Auth0 RBAC permissions in the JWT. Fine-grained ownership checks happen in services. A resource that exists but isn't yours returns 404, which prevents ID enumeration.
Booking state machine
confirm (owner, payment authorized) start (owner, handover)
pending ───────────────────────────────► confirmed ─────────────────► active
│ decline (owner) / cancel (renter) / │ cancel (either; refund │ complete (owner)
│ expire (job) / payment failed (webhook) │ per policy) ▼
└──────────────► cancelled ◄────────────────┘ completed
dispute (either) ─┐ │ dispute (≤48h)
active ──────────────────────► disputed ◄┘
resolve (admin) → completed
Refund policy
Refunds apply to the subtotal. The service fee is refunded only on a 100% refund.
| Policy | 100% | 50% | 0% |
|---|---|---|---|
| flexible | ≥ 1 day before start | < 1 day | n/a |
| moderate | ≥ 5 days | ≥ 1 day | < 1 day |
| strict | ≥ 14 days, or within 48h of booking | ≥ 7 days | < 7 days |
If the owner declines or cancels, the renter always gets 100%.
2. Endpoint Table
Auth column legend
- Public: no token needed. If a token is sent, it is still validated.
- Bearer: any valid token.
scope: the token must carry that permission.- Party: the renter or owner on the booking or conversation.
- Owner: owns the listing.
Auth0 RBAC role → permissions
renter:profile:write bookings:write reviews:write messages:writeowner: renter permissions +listings:write bookings:manage payouts:readadmin: all of the above +admin:all
| Method | Path | Purpose | Auth |
|---|---|---|---|
| GET | /api/v1/me |
Current user profile (private fields) | Bearer |
| PATCH | /api/v1/me |
Update name/phone | profile:write |
| POST | /api/v1/me/owner-onboarding |
Create/resume Stripe Connect onboarding link; grants owner role |
profile:write |
| GET | /api/v1/users/{userId} |
Public profile | Public |
| GET | /api/v1/users/{userId}/reviews |
Published reviews about a user | Public |
| GET | /api/v1/categories |
Category tree | Public (CDN-cached) |
| GET | /api/v1/listings |
Search: geo radius, dates, category, price, condition, text | Public (CDN-cached 30s) |
| POST | /api/v1/listings |
Create draft listing | listings:write |
| GET | /api/v1/listings/{listingId} |
Listing detail (drafts visible only to the owner) | Public |
| PATCH | /api/v1/listings/{listingId} |
Partial update (If-Match for optimistic concurrency) |
listings:write + Owner |
| DELETE | /api/v1/listings/{listingId} |
Archive (409 if upcoming bookings) | listings:write + Owner |
| POST | /api/v1/listings/{listingId}/publish |
Publish (requires photos + payouts enabled) | listings:write + Owner |
| POST | /api/v1/listings/{listingId}/pause |
Pause (hidden from search) | listings:write + Owner |
| POST | /api/v1/listings/{listingId}/photos |
Get presigned S3 upload URL | listings:write + Owner |
| GET | /api/v1/listings/{listingId}/availability |
Day-by-day calendar (≤ 180 days) | Public |
| POST | /api/v1/listings/{listingId}/blocks |
Owner blocks dates | listings:write + Owner |
| DELETE | /api/v1/listings/{listingId}/blocks/{slotId} |
Remove a block | listings:write + Owner |
| GET | /api/v1/listings/{listingId}/quote |
Price breakdown + availability for a date range | Public |
| GET | /api/v1/listings/{listingId}/reviews |
Published listing reviews | Public |
| GET | /api/v1/bookings |
My bookings (role=renter|owner) |
Bearer (bookings:manage for role=owner) |
| POST | /api/v1/bookings |
Request booking + authorize payment (Idempotency-Key required) | bookings:write |
| GET | /api/v1/bookings/{bookingId} |
Booking detail | Party or admin |
| POST | /api/v1/bookings/{bookingId}/confirm |
Owner accepts → capture rental | bookings:manage + Owner |
| POST | /api/v1/bookings/{bookingId}/decline |
Owner declines → void auth | bookings:manage + Owner |
| POST | /api/v1/bookings/{bookingId}/cancel |
Cancel → refund per policy (Idempotency-Key) | bookings:write + Party |
| POST | /api/v1/bookings/{bookingId}/start |
Handover → active |
bookings:manage + Owner |
| POST | /api/v1/bookings/{bookingId}/complete |
Return confirmed → release deposit | bookings:manage + Owner |
| POST | /api/v1/bookings/{bookingId}/dispute |
Open dispute / deposit claim | bookings:write + Party |
| POST | /api/v1/bookings/{bookingId}/reviews |
Leave review (completed bookings, ≤ 14 days) | reviews:write + Party |
| GET | /api/v1/conversations |
My conversations | Bearer |
| POST | /api/v1/conversations |
Start (or return existing) listing Q&A thread | messages:write |
| GET | /api/v1/conversations/{conversationId}/messages |
Messages (cursor, newest first) | Party |
| POST | /api/v1/conversations/{conversationId}/messages |
Send message | messages:write + Party |
| POST | /api/v1/conversations/{conversationId}/read |
Mark read up to now | Party |
| GET | /api/v1/payouts |
Owner payout history | payouts:read |
| POST | /api/v1/webhooks/stripe |
Stripe events (signature-verified) | Stripe signature |
| POST | /api/v1/admin/bookings/{bookingId}/resolve-dispute |
Resolve dispute, split deposit | admin:all |
| POST | /api/v1/admin/users/{userId}/suspend |
Suspend user (blocks API access within 60s) | admin:all |
Collection conventions
- Pagination is cursor/keyset based:
?limit=20&cursor=<opaque>. The default limit is 20 and the maximum is 100. The response shape is{ "data": [...], "page": { "next_cursor": "…", "has_more": true, "limit": 20 } }. Total counts are omitted becauseCOUNT(*)over geo and date filters is expensive. With keyset pagination, deep pages cost the same as page 1. - Filtering uses flat, typed query params, for example
category=tents&lat=..&lng=..&radius_km=25&start_date=..&end_date=..&min_price_cents=..&condition=new,good. Unknown params return 400, so typos fail loudly. - Sorting uses
sort=<field>for ascending andsort=-<field>for descending. The allowed values are a whitelist per endpoint.idis always the tiebreaker.
Status codes
| Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created (with Location header) |
| 204 | No content |
| 400 | Malformed request or unknown parameter |
| 401 | Missing or invalid token |
| 403 | Missing scope or suspended account |
| 404 | Not found, or not yours |
| 409 | State conflict, dates unavailable, or idempotency in progress |
| 412 | If-Match mismatch |
| 422 | Field validation failed |
| 429 | Rate limited (with Retry-After) |
| 502 | Payment provider error |
All errors use application/problem+json.
3. OpenAPI 3.0 Specification
openapi: 3.0.3
info:
title: GearLoop API
version: 1.0.0
description: |
Peer-to-peer outdoor gear rental marketplace.
Conventions
- JSON bodies use snake_case. Money is integer minor units (`*_cents`) plus ISO 4217 `currency`.
- Dates are `YYYY-MM-DD` in the listing's local timezone. Ranges are half-open `[start_date, end_date)`.
- Collections use cursor pagination (`cursor`, `limit`) and return `{ data, page }`.
- Errors are RFC 7807 `application/problem+json` with a stable machine-readable `code`.
- Unsafe, money-moving POSTs require an `Idempotency-Key` header (replayed for 24h).
contact:
name: GearLoop Platform Team
url: https://docs.gearloop.com
servers:
- url: https://api.gearloop.com/api/v1
description: Production
- url: https://api.staging.gearloop.com/api/v1
description: Staging
security:
- auth0: []
tags:
- name: Me
- name: Users
- name: Categories
- name: Listings
- name: Availability
- name: Bookings
- name: Reviews
- name: Messaging
- name: Payouts
- name: Webhooks
- name: Admin
paths:
/me:
get:
tags: [Me]
operationId: getMe
summary: Get the authenticated user's private profile
responses:
'200':
description: Current user
content:
application/json:
schema: { $ref: '#/components/schemas/UserPrivate' }
'401': { $ref: '#/components/responses/Unauthorized' }
patch:
tags: [Me]
operationId: updateMe
summary: Update the authenticated user's profile
security:
- auth0: ['profile:write']
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/UserUpdate' }
responses:
'200':
description: Updated user
content:
application/json:
schema: { $ref: '#/components/schemas/UserPrivate' }
'401': { $ref: '#/components/responses/Unauthorized' }
'403': { $ref: '#/components/responses/Forbidden' }
'422': { $ref: '#/components/responses/ValidationFailed' }
/me/owner-onboarding:
post:
tags: [Me]
operationId: startOwnerOnboarding
summary: Create or resume Stripe Connect onboarding
description: Grants the `owner` role (refresh your token afterwards) and returns a short-lived hosted onboarding URL.
security:
- auth0: ['profile:write']
responses:
'200':
description: Onboarding link
content:
application/json:
schema: { $ref: '#/components/schemas/OwnerOnboardingLink' }
'401': { $ref: '#/components/responses/Unauthorized' }
'429': { $ref: '#/components/responses/TooManyRequests' }
/users/{userId}:
get:
tags: [Users]
operationId: getUser
summary: Get a public user profile
security: [{}]
parameters:
- $ref: '#/components/parameters/UserId'
responses:
'200':
description: Public profile
content:
application/json:
schema: { $ref: '#/components/schemas/UserPublic' }
'404': { $ref: '#/components/responses/NotFound' }
/users/{userId}/reviews:
get:
tags: [Reviews]
operationId: listUserReviews
summary: List published reviews about a user
security: [{}]
parameters:
- $ref: '#/components/parameters/UserId'
- $ref: '#/components/parameters/Cursor'
- $ref: '#/components/parameters/Limit'
responses:
'200':
description: Reviews
content:
application/json:
schema: { $ref: '#/components/schemas/ReviewPage' }
'404': { $ref: '#/components/responses/NotFound' }
/categories:
get:
tags: [Categories]
operationId: listCategories
summary: Get the full category tree
security: [{}]
responses:
'200':
description: Category tree (root nodes with nested children)
headers:
Cache-Control: { $ref: '#/components/headers/CacheControl' }
ETag: { $ref: '#/components/headers/ETag' }
content:
application/json:
schema:
type: object
required: [data]
properties:
data:
type: array
items: { $ref: '#/components/schemas/Category' }
/listings:
get:
tags: [Listings]
operationId: searchListings
summary: Search published listings
security: [{}]
parameters:
- name: q
in: query
description: Full-text query over title and description
schema: { type: string, maxLength: 100 }
- name: category
in: query
description: Category slug. Includes all descendant categories.
schema: { type: string, pattern: '^[a-z0-9-]+$', example: tents }
- name: lat
in: query
description: Latitude. Must be provided together with lng.
schema: { type: number, format: double, minimum: -90, maximum: 90 }
- name: lng
in: query
schema: { type: number, format: double, minimum: -180, maximum: 180 }
- name: radius_km
in: query
schema: { type: integer, minimum: 1, maximum: 200, default: 25 }
- name: start_date
in: query
description: Only return listings fully available for [start_date, end_date)
schema: { type: string, format: date }
- name: end_date
in: query
schema: { type: string, format: date }
- name: min_price_cents
in: query
schema: { type: integer, minimum: 0 }
- name: max_price_cents
in: query
schema: { type: integer, minimum: 0 }
- name: condition
in: query
style: form
explode: false
schema:
type: array
items: { $ref: '#/components/schemas/ListingCondition' }
- name: sort
in: query
description: "`distance` requires lat/lng. Default is `distance` when lat/lng are present, otherwise `-created_at`."
schema:
type: string
enum: [distance, price, -price, -created_at, -rating]
- $ref: '#/components/parameters/Cursor'
- $ref: '#/components/parameters/Limit'
responses:
'200':
description: Search results
headers:
Cache-Control: { $ref: '#/components/headers/CacheControl' }
content:
application/json:
schema: { $ref: '#/components/schemas/ListingSummaryPage' }
'400': { $ref: '#/components/responses/BadRequest' }
'422': { $ref: '#/components/responses/ValidationFailed' }
'429': { $ref: '#/components/responses/TooManyRequests' }
post:
tags: [Listings]
operationId: createListing
summary: Create a draft listing
security:
- auth0: ['listings:write']
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/ListingCreate' }
responses:
'201':
description: Draft listing created
headers:
Location: { $ref: '#/components/headers/Location' }
ETag: { $ref: '#/components/headers/ETag' }
content:
application/json:
schema: { $ref: '#/components/schemas/Listing' }
'401': { $ref: '#/components/responses/Unauthorized' }
'403': { $ref: '#/components/responses/Forbidden' }
'422': { $ref: '#/components/responses/ValidationFailed' }
/listings/{listingId}:
parameters:
- $ref: '#/components/parameters/ListingId'
get:
tags: [Listings]
operationId: getListing
summary: Get a listing
description: Drafts, paused and archived listings are only visible to their owner. Public coordinates are approximate (about 500 m).
security:
- {}
- auth0: []
responses:
'200':
description: Listing
headers:
ETag: { $ref: '#/components/headers/ETag' }
content:
application/json:
schema: { $ref: '#/components/schemas/Listing' }
'404': { $ref: '#/components/responses/NotFound' }
patch:
tags: [Listings]
operationId: updateListing
summary: Partially update a listing
security:
- auth0: ['listings:write']
parameters:
- $ref: '#/components/parameters/IfMatch'
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/ListingUpdate' }
responses:
'200':
description: Updated listing
headers:
ETag: { $ref: '#/components/headers/ETag' }
content:
application/json:
schema: { $ref: '#/components/schemas/Listing' }
'401': { $ref: '#/components/responses/Unauthorized' }
'403': { $ref: '#/components/responses/Forbidden' }
'404': { $ref: '#/components/responses/NotFound' }
'412': { $ref: '#/components/responses/PreconditionFailed' }
'422': { $ref: '#/components/responses/ValidationFailed' }
delete:
tags: [Listings]
operationId: archiveListing
summary: Archive a listing
security:
- auth0: ['listings:write']
responses:
'204': { description: Archived }
'401': { $ref: '#/components/responses/Unauthorized' }
'404': { $ref: '#/components/responses/NotFound' }
'409': { $ref: '#/components/responses/Conflict' }
/listings/{listingId}/publish:
post:
tags: [Listings]
operationId: publishListing
summary: Publish a listing
description: Requires at least one photo and a Stripe Connect account with payouts enabled.
security:
- auth0: ['listings:write']
parameters:
- $ref: '#/components/parameters/ListingId'
responses:
'200':
description: Published listing
content:
application/json:
schema: { $ref: '#/components/schemas/Listing' }
'404': { $ref: '#/components/responses/NotFound' }
'409': { $ref: '#/components/responses/Conflict' }
'422': { $ref: '#/components/responses/ValidationFailed' }
/listings/{listingId}/pause:
post:
tags: [Listings]
operationId: pauseListing
summary: Pause a published listing (existing bookings are unaffected)
security:
- auth0: ['listings:write']
parameters:
- $ref: '#/components/parameters/ListingId'
responses:
'200':
description: Paused listing
content:
application/json:
schema: { $ref: '#/components/schemas/Listing' }
'404': { $ref: '#/components/responses/NotFound' }
'409': { $ref: '#/components/responses/Conflict' }
/listings/{listingId}/photos:
post:
tags: [Listings]
operationId: createPhotoUpload
summary: Get a presigned URL to upload a listing photo
security:
- auth0: ['listings:write']
parameters:
- $ref: '#/components/parameters/ListingId'
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/PhotoUploadRequest' }
responses:
'201':
description: Presigned upload
content:
application/json:
schema: { $ref: '#/components/schemas/PhotoUpload' }
'404': { $ref: '#/components/responses/NotFound' }
'422': { $ref: '#/components/responses/ValidationFailed' }
/listings/{listingId}/availability:
get:
tags: [Availability]
operationId: getAvailability
summary: Get the availability calendar
security: [{}]
parameters:
- $ref: '#/components/parameters/ListingId'
- name: from
in: query
required: true
schema: { type: string, format: date }
- name: to
in: query
required: true
description: Exclusive. At most 180 days after `from`.
schema: { type: string, format: date }
responses:
'200':
description: Calendar
content:
application/json:
schema: { $ref: '#/components/schemas/AvailabilityCalendar' }
'404': { $ref: '#/components/responses/NotFound' }
'422': { $ref: '#/components/responses/ValidationFailed' }
/listings/{listingId}/blocks:
post:
tags: [Availability]
operationId: createBlock
summary: Block a date range
security:
- auth0: ['listings:write']
parameters:
- $ref: '#/components/parameters/ListingId'
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/BlockCreate' }
responses:
'201':
description: Block created
content:
application/json:
schema: { $ref: '#/components/schemas/AvailabilitySlot' }
'404': { $ref: '#/components/responses/NotFound' }
'409': { $ref: '#/components/responses/Conflict' }
'422': { $ref: '#/components/responses/ValidationFailed' }
/listings/{listingId}/blocks/{slotId}:
delete:
tags: [Availability]
operationId: deleteBlock
summary: Remove an owner block
security:
- auth0: ['listings:write']
parameters:
- $ref: '#/components/parameters/ListingId'
- $ref: '#/components/parameters/SlotId'
responses:
'204': { description: Removed }
'404': { $ref: '#/components/responses/NotFound' }
/listings/{listingId}/quote:
get:
tags: [Listings]
operationId: getQuote
summary: Get an authoritative price breakdown for a date range
security: [{}]
parameters:
- $ref: '#/components/parameters/ListingId'
- name: start_date
in: query
required: true
schema: { type: string, format: date }
- name: end_date
in: query
required: true
schema: { type: string, format: date }
responses:
'200':
description: Quote
content:
application/json:
schema: { $ref: '#/components/schemas/Quote' }
'404': { $ref: '#/components/responses/NotFound' }
'422': { $ref: '#/components/responses/ValidationFailed' }
/listings/{listingId}/reviews:
get:
tags: [Reviews]
operationId: listListingReviews
summary: List published reviews for a listing
security: [{}]
parameters:
- $ref: '#/components/parameters/ListingId'
- $ref: '#/components/parameters/Cursor'
- $ref: '#/components/parameters/Limit'
responses:
'200':
description: Reviews
content:
application/json:
schema: { $ref: '#/components/schemas/ReviewPage' }
'404': { $ref: '#/components/responses/NotFound' }
/bookings:
get:
tags: [Bookings]
operationId: listBookings
summary: List my bookings as renter or owner
parameters:
- name: role
in: query
schema: { type: string, enum: [renter, owner], default: renter }
- name: status
in: query
style: form
explode: false
schema:
type: array
items: { $ref: '#/components/schemas/BookingStatus' }
- name: sort
in: query
schema: { type: string, enum: [-created_at, start_date], default: -created_at }
- $ref: '#/components/parameters/Cursor'
- $ref: '#/components/parameters/Limit'
responses:
'200':
description: Bookings
content:
application/json:
schema: { $ref: '#/components/schemas/BookingPage' }
'401': { $ref: '#/components/responses/Unauthorized' }
'403': { $ref: '#/components/responses/Forbidden' }
post:
tags: [Bookings]
operationId: createBooking
summary: Request a booking and authorize payment
description: |
Places a hold on the dates and creates a manual-capture Stripe PaymentIntent.
The client completes payment with `payment_client_secret` (Stripe.js / mobile SDK).
The hold expires in 30 minutes if payment is not authorized, then the owner has 24 hours to confirm.
security:
- auth0: ['bookings:write']
parameters:
- $ref: '#/components/parameters/IdempotencyKey'
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/BookingCreate' }
responses:
'201':
description: Booking created (status `pending`)
headers:
Location: { $ref: '#/components/headers/Location' }
content:
application/json:
schema: { $ref: '#/components/schemas/BookingCreated' }
'400': { $ref: '#/components/responses/BadRequest' }
'401': { $ref: '#/components/responses/Unauthorized' }
'403': { $ref: '#/components/responses/Forbidden' }
'404': { $ref: '#/components/responses/NotFound' }
'409': { $ref: '#/components/responses/Conflict' }
'422': { $ref: '#/components/responses/ValidationFailed' }
'429': { $ref: '#/components/responses/TooManyRequests' }
'502': { $ref: '#/components/responses/BadGateway' }
/bookings/{bookingId}:
get:
tags: [Bookings]
operationId: getBooking
summary: Get a booking (parties and admins only)
parameters:
- $ref: '#/components/parameters/BookingId'
responses:
'200': { $ref: '#/components/responses/BookingOk' }
'401': { $ref: '#/components/responses/Unauthorized' }
'404': { $ref: '#/components/responses/NotFound' }
/bookings/{bookingId}/confirm:
post:
tags: [Bookings]
operationId: confirmBooking
summary: Owner accepts a pending booking (rental is captured)
security:
- auth0: ['bookings:manage']
parameters:
- $ref: '#/components/parameters/BookingId'
responses:
'200': { $ref: '#/components/responses/BookingOk' }
'403': { $ref: '#/components/responses/Forbidden' }
'404': { $ref: '#/components/responses/NotFound' }
'409': { $ref: '#/components/responses/Conflict' }
/bookings/{bookingId}/decline:
post:
tags: [Bookings]
operationId: declineBooking
summary: Owner declines a pending booking (authorization voided)
security:
- auth0: ['bookings:manage']
parameters:
- $ref: '#/components/parameters/BookingId'
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/ReasonRequest' }
responses:
'200': { $ref: '#/components/responses/BookingOk' }
'404': { $ref: '#/components/responses/NotFound' }
'409': { $ref: '#/components/responses/Conflict' }
'422': { $ref: '#/components/responses/ValidationFailed' }
/bookings/{bookingId}/cancel:
post:
tags: [Bookings]
operationId: cancelBooking
summary: Cancel a pending or confirmed booking (refund per cancellation policy)
security:
- auth0: ['bookings:write']
parameters:
- $ref: '#/components/parameters/BookingId'
- $ref: '#/components/parameters/IdempotencyKey'
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/ReasonRequest' }
responses:
'200': { $ref: '#/components/responses/BookingOk' }
'404': { $ref: '#/components/responses/NotFound' }
'409': { $ref: '#/components/responses/Conflict' }
'422': { $ref: '#/components/responses/ValidationFailed' }
/bookings/{bookingId}/start:
post:
tags: [Bookings]
operationId: startBooking
summary: Owner records gear handover (allowed from 1 day before start_date)
security:
- auth0: ['bookings:manage']
parameters:
- $ref: '#/components/parameters/BookingId'
responses:
'200': { $ref: '#/components/responses/BookingOk' }
'404': { $ref: '#/components/responses/NotFound' }
'409': { $ref: '#/components/responses/Conflict' }
/bookings/{bookingId}/complete:
post:
tags: [Bookings]
operationId: completeBooking
summary: Owner confirms return (deposit hold released)
security:
- auth0: ['bookings:manage']
parameters:
- $ref: '#/components/parameters/BookingId'
responses:
'200': { $ref: '#/components/responses/BookingOk' }
'404': { $ref: '#/components/responses/NotFound' }
'409': { $ref: '#/components/responses/Conflict' }
/bookings/{bookingId}/dispute:
post:
tags: [Bookings]
operationId: disputeBooking
summary: Open a dispute (active, or within 48h of completion)
security:
- auth0: ['bookings:write']
parameters:
- $ref: '#/components/parameters/BookingId'
- $ref: '#/components/parameters/IdempotencyKey'
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/DisputeCreate' }
responses:
'200': { $ref: '#/components/responses/BookingOk' }
'404': { $ref: '#/components/responses/NotFound' }
'409': { $ref: '#/components/responses/Conflict' }
'422': { $ref: '#/components/responses/ValidationFailed' }
/bookings/{bookingId}/reviews:
post:
tags: [Reviews]
operationId: createReview
summary: Review the other party of a completed booking
description: The renter reviews the listing (rolls up to the owner); the owner reviews the renter. Reviews become visible when both are submitted or after 14 days.
security:
- auth0: ['reviews:write']
parameters:
- $ref: '#/components/parameters/BookingId'
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/ReviewCreate' }
responses:
'201':
description: Review recorded
content:
application/json:
schema: { $ref: '#/components/schemas/Review' }
'404': { $ref: '#/components/responses/NotFound' }
'409': { $ref: '#/components/responses/Conflict' }
'422': { $ref: '#/components/responses/ValidationFailed' }
/conversations:
get:
tags: [Messaging]
operationId: listConversations
summary: List my conversations, most recently active first
parameters:
- $ref: '#/components/parameters/Cursor'
- $ref: '#/components/parameters/Limit'
responses:
'200':
description: Conversations
content:
application/json:
schema: { $ref: '#/components/schemas/ConversationPage' }
'401': { $ref: '#/components/responses/Unauthorized' }
post:
tags: [Messaging]
operationId: createConversation
summary: Start a Q&A thread about a listing (returns the existing thread if one exists)
security:
- auth0: ['messages:write']
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/ConversationCreate' }
responses:
'200':
description: Existing conversation returned; message appended
content:
application/json:
schema: { $ref: '#/components/schemas/Conversation' }
'201':
description: Conversation created
headers:
Location: { $ref: '#/components/headers/Location' }
content:
application/json:
schema: { $ref: '#/components/schemas/Conversation' }
'404': { $ref: '#/components/responses/NotFound' }
'422': { $ref: '#/components/responses/ValidationFailed' }
'429': { $ref: '#/components/responses/TooManyRequests' }
/conversations/{conversationId}/messages:
parameters:
- $ref: '#/components/parameters/ConversationId'
get:
tags: [Messaging]
operationId: listMessages
summary: List messages, newest first
parameters:
- $ref: '#/components/parameters/Cursor'
- $ref: '#/components/parameters/Limit'
responses:
'200':
description: Messages
content:
application/json:
schema: { $ref: '#/components/schemas/MessagePage' }
'404': { $ref: '#/components/responses/NotFound' }
post:
tags: [Messaging]
operationId: sendMessage
summary: Send a message
security:
- auth0: ['messages:write']
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/MessageCreate' }
responses:
'201':
description: Message sent
content:
application/json:
schema: { $ref: '#/components/schemas/Message' }
'404': { $ref: '#/components/responses/NotFound' }
'422': { $ref: '#/components/responses/ValidationFailed' }
'429': { $ref: '#/components/responses/TooManyRequests' }
/conversations/{conversationId}/read:
post:
tags: [Messaging]
operationId: markConversationRead
summary: Mark all messages from the other party as read
parameters:
- $ref: '#/components/parameters/ConversationId'
responses:
'204': { description: Marked read }
'404': { $ref: '#/components/responses/NotFound' }
/payouts:
get:
tags: [Payouts]
operationId: listPayouts
summary: List my payouts (owners)
security:
- auth0: ['payouts:read']
parameters:
- $ref: '#/components/parameters/Cursor'
- $ref: '#/components/parameters/Limit'
responses:
'200':
description: Payouts
content:
application/json:
schema: { $ref: '#/components/schemas/PayoutPage' }
'403': { $ref: '#/components/responses/Forbidden' }
/webhooks/stripe:
post:
tags: [Webhooks]
operationId: stripeWebhook
summary: Receive Stripe events
description: Verified using the `Stripe-Signature` header over the raw body. Events are deduplicated by event id and processed asynchronously.
security:
- stripeSignature: []
requestBody:
required: true
content:
application/json:
schema: { type: object, additionalProperties: true }
responses:
'200':
description: Accepted
content:
application/json:
schema:
type: object
properties:
received: { type: boolean, example: true }
'400': { $ref: '#/components/responses/BadRequest' }
/admin/bookings/{bookingId}/resolve-dispute:
post:
tags: [Admin]
operationId: resolveDispute
summary: Resolve a dispute and split the deposit
security:
- auth0: ['admin:all']
parameters:
- $ref: '#/components/parameters/BookingId'
- $ref: '#/components/parameters/IdempotencyKey'
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/DisputeResolution' }
responses:
'200': { $ref: '#/components/responses/BookingOk' }
'403': { $ref: '#/components/responses/Forbidden' }
'404': { $ref: '#/components/responses/NotFound' }
'409': { $ref: '#/components/responses/Conflict' }
/admin/users/{userId}/suspend:
post:
tags: [Admin]
operationId: suspendUser
summary: Suspend a user (API access revoked within 60 seconds)
security:
- auth0: ['admin:all']
parameters:
- $ref: '#/components/parameters/UserId'
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/ReasonRequest' }
responses:
'204': { description: Suspended }
'403': { $ref: '#/components/responses/Forbidden' }
'404': { $ref: '#/components/responses/NotFound' }
components:
securitySchemes:
auth0:
type: oauth2
description: Auth0 Authorization Code + PKCE. Access tokens are RS256 JWTs (15 min) with a `permissions` claim. Refresh tokens rotate with reuse detection.
flows:
authorizationCode:
authorizationUrl: https://auth.gearloop.com/authorize
tokenUrl: https://auth.gearloop.com/oauth/token
refreshUrl: https://auth.gearloop.com/oauth/token
scopes:
'profile:write': Update own profile
'bookings:write': Create, cancel and dispute own bookings as renter
'bookings:manage': Confirm, decline, start and complete bookings on own listings
'listings:write': Create and manage own listings
'reviews:write': Write reviews for own completed bookings
'messages:write': Send messages
'payouts:read': View own payouts
'admin:all': Administrative operations
stripeSignature:
type: apiKey
in: header
name: Stripe-Signature
parameters:
ListingId:
name: listingId
in: path
required: true
schema: { type: string, format: uuid }
BookingId:
name: bookingId
in: path
required: true
schema: { type: string, format: uuid }
ConversationId:
name: conversationId
in: path
required: true
schema: { type: string, format: uuid }
UserId:
name: userId
in: path
required: true
schema: { type: string, format: uuid }
SlotId:
name: slotId
in: path
required: true
schema: { type: string, format: uuid }
Cursor:
name: cursor
in: query
description: Opaque cursor from `page.next_cursor`
schema: { type: string, maxLength: 512 }
Limit:
name: limit
in: query
schema: { type: integer, minimum: 1, maximum: 100, default: 20 }
IdempotencyKey:
name: Idempotency-Key
in: header
required: true
description: Client-generated unique key (UUIDv4 recommended). Identical retries within 24h replay the original response.
schema: { type: string, minLength: 8, maxLength: 255, pattern: '^[A-Za-z0-9_-]+$' }
IfMatch:
name: If-Match
in: header
required: false
description: ETag from a previous GET. If it no longer matches, the request fails with 412.
schema: { type: string, example: 'W/"7"' }
headers:
Location:
description: URL of the created resource
schema: { type: string, format: uri }
ETag:
description: Weak entity tag derived from the resource version
schema: { type: string }
CacheControl:
schema: { type: string, example: 'public, max-age=30, stale-while-revalidate=60' }
RetryAfter:
description: Seconds to wait before retrying
schema: { type: integer }
responses:
BookingOk:
description: Booking
content:
application/json:
schema: { $ref: '#/components/schemas/Booking' }
BadRequest:
description: Malformed request or unknown parameter
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
Unauthorized:
description: Missing, expired or invalid access token
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
Forbidden:
description: Insufficient scope or suspended account
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
NotFound:
description: Resource not found or not accessible
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
Conflict:
description: State conflict (dates_unavailable, invalid_state_transition, price_changed, idempotency_in_progress)
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
PreconditionFailed:
description: If-Match did not match the current version
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
ValidationFailed:
description: One or more fields are invalid
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
example:
type: https://docs.gearloop.com/errors/validation_failed
title: Request validation failed
status: 422
code: validation_failed
instance: /api/v1/bookings
request_id: 6f1c2e0a-5d7b-4d1e-9f0a-2b7c1d9e8a11
errors:
- field: end_date
message: end_date must be after start_date
code: invalid_range
TooManyRequests:
description: Rate limit exceeded
headers:
Retry-After: { $ref: '#/components/headers/RetryAfter' }
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
BadGateway:
description: Upstream payment provider error; safe to retry with the same Idempotency-Key
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
schemas:
Problem:
type: object
required: [type, title, status, code]
properties:
type: { type: string, format: uri }
title: { type: string }
status: { type: integer }
code: { type: string, description: Stable machine-readable error code }
detail: { type: string }
instance: { type: string }
request_id: { type: string }
errors:
type: array
items:
type: object
required: [field, message]
properties:
field: { type: string }
message: { type: string }
code: { type: string }
PageInfo:
type: object
required: [has_more, limit]
properties:
next_cursor: { type: string, nullable: true }
has_more: { type: boolean }
limit: { type: integer }
Currency:
type: string
pattern: '^[A-Z]{3}$'
example: USD
UserSummary:
type: object
required: [id, display_name, is_verified]
properties:
id: { type: string, format: uuid }
display_name: { type: string, example: Jamie R. }
avatar_url: { type: string, format: uri, nullable: true }
is_verified: { type: boolean }
UserPublic:
allOf:
- $ref: '#/components/schemas/UserSummary'
- type: object
properties:
rating_avg: { type: number, format: float, nullable: true }
rating_count: { type: integer }
member_since: { type: string, format: date-time }
UserPrivate:
type: object
required: [id, email, full_name, roles, is_verified, created_at, updated_at]
properties:
id: { type: string, format: uuid }
email: { type: string, format: email }
full_name: { type: string }
phone: { type: string, nullable: true, example: '+14155550123' }
roles:
type: array
items: { type: string, enum: [renter, owner, admin] }
is_verified: { type: boolean }
owner_payouts_enabled: { type: boolean }
created_at: { type: string, format: date-time }
updated_at: { type: string, format: date-time }
UserUpdate:
type: object
minProperties: 1
additionalProperties: false
properties:
full_name: { type: string, minLength: 1, maxLength: 120 }
phone: { type: string, pattern: '^\+[1-9]\d{6,14}$', description: E.164 format }
OwnerOnboardingLink:
type: object
required: [url, expires_at, payouts_enabled]
properties:
url: { type: string, format: uri }
expires_at: { type: string, format: date-time }
payouts_enabled: { type: boolean }
Category:
type: object
required: [id, name, slug]
properties:
id: { type: string, format: uuid }
name: { type: string, example: Tents }
slug: { type: string, example: tents }
parent_id: { type: string, format: uuid, nullable: true }
icon_url: { type: string, format: uri, nullable: true }
children:
type: array
items: { $ref: '#/components/schemas/Category' }
ListingCondition:
type: string
enum: [new, good, fair]
CancellationPolicy:
type: string
enum: [flexible, moderate, strict]
ListingStatus:
type: string
enum: [draft, published, paused, archived]
LocationInput:
type: object
required: [lat, lng, city, region, country]
additionalProperties: false
properties:
lat: { type: number, format: double, minimum: -90, maximum: 90 }
lng: { type: number, format: double, minimum: -180, maximum: 180 }
city: { type: string, maxLength: 100 }
region: { type: string, maxLength: 100 }
country: { type: string, pattern: '^[A-Z]{2}$' }
Location:
allOf:
- $ref: '#/components/schemas/LocationInput'
- type: object
properties:
timezone: { type: string, readOnly: true, example: America/Denver }
is_approximate: { type: boolean, readOnly: true }
ListingCreate:
type: object
additionalProperties: false
required: [category_id, title, description, daily_price_cents, currency, condition, cancellation_policy, location]
properties:
category_id: { type: string, format: uuid }
title: { type: string, minLength: 5, maxLength: 120 }
description: { type: string, minLength: 20, maxLength: 5000 }
daily_price_cents: { type: integer, minimum: 100, maximum: 1000000 }
currency: { $ref: '#/components/schemas/Currency' }
deposit_cents: { type: integer, minimum: 0, maximum: 500000, default: 0 }
condition: { $ref: '#/components/schemas/ListingCondition' }
cancellation_policy: { $ref: '#/components/schemas/CancellationPolicy' }
location: { $ref: '#/components/schemas/LocationInput' }
photos:
type: array
maxItems: 12
items: { type: string, format: uri }
ListingUpdate:
type: object
minProperties: 1
additionalProperties: false
properties:
category_id: { type: string, format: uuid }
title: { type: string, minLength: 5, maxLength: 120 }
description: { type: string, minLength: 20, maxLength: 5000 }
daily_price_cents: { type: integer, minimum: 100, maximum: 1000000 }
deposit_cents: { type: integer, minimum: 0, maximum: 500000 }
condition: { $ref: '#/components/schemas/ListingCondition' }
cancellation_policy: { $ref: '#/components/schemas/CancellationPolicy' }
location: { $ref: '#/components/schemas/LocationInput' }
photos:
type: array
maxItems: 12
items: { type: string, format: uri }
Listing:
type: object
required: [id, owner, category, title, description, daily_price_cents, currency, deposit_cents, condition, cancellation_policy, status, location, photos, version, created_at, updated_at]
properties:
id: { type: string, format: uuid }
owner: { $ref: '#/components/schemas/UserSummary' }
category:
type: object
properties:
id: { type: string, format: uuid }
name: { type: string }
slug: { type: string }
title: { type: string }
description: { type: string }
daily_price_cents: { type: integer }
currency: { $ref: '#/components/schemas/Currency' }
deposit_cents: { type: integer }
condition: { $ref: '#/components/schemas/ListingCondition' }
cancellation_policy: { $ref: '#/components/schemas/CancellationPolicy' }
status: { $ref: '#/components/schemas/ListingStatus' }
location: { $ref: '#/components/schemas/Location' }
photos:
type: array
items: { type: string, format: uri }
rating_avg: { type: number, format: float, nullable: true }
rating_count: { type: integer }
version: { type: integer }
created_at: { type: string, format: date-time }
updated_at: { type: string, format: date-time }
ListingSummary:
type: object
required: [id, title, daily_price_cents, currency, condition, city, region, category_slug]
properties:
id: { type: string, format: uuid }
title: { type: string }
daily_price_cents: { type: integer }
currency: { $ref: '#/components/schemas/Currency' }
condition: { $ref: '#/components/schemas/ListingCondition' }
city: { type: string }
region: { type: string }
approx_lat: { type: number, format: double }
approx_lng: { type: number, format: double }
cover_photo_url: { type: string, format: uri, nullable: true }
category_slug: { type: string }
rating_avg: { type: number, format: float, nullable: true }
rating_count: { type: integer }
distance_m: { type: number, nullable: true }
ListingSummaryPage:
type: object
required: [data, page]
properties:
data:
type: array
items: { $ref: '#/components/schemas/ListingSummary' }
page: { $ref: '#/components/schemas/PageInfo' }
PhotoUploadRequest:
type: object
required: [content_type, byte_size]
additionalProperties: false
properties:
content_type: { type: string, enum: [image/jpeg, image/png, image/webp] }
byte_size: { type: integer, minimum: 1, maximum: 10485760 }
PhotoUpload:
type: object
required: [upload_url, photo_url, expires_at]
properties:
upload_url: { type: string, format: uri, description: Presigned PUT URL (5 min) }
photo_url: { type: string, format: uri, description: Public CDN URL to add to `photos` after upload }
expires_at: { type: string, format: date-time }
AvailabilityCalendar:
type: object
required: [listing_id, from, to, days]
properties:
listing_id: { type: string, format: uuid }
from: { type: string, format: date }
to: { type: string, format: date }
days:
type: array
items:
type: object
required: [date, status]
properties:
date: { type: string, format: date }
status: { type: string, enum: [available, booked, blocked] }
AvailabilitySlot:
type: object
required: [id, listing_id, start_date, end_date, kind]
properties:
id: { type: string, format: uuid }
listing_id: { type: string, format: uuid }
start_date: { type: string, format: date }
end_date: { type: string, format: date }
kind: { type: string, enum: [blocked, booked] }
note: { type: string, nullable: true }
BlockCreate:
type: object
required: [start_date, end_date]
additionalProperties: false
properties:
start_date: { type: string, format: date }
end_date: { type: string, format: date }
note: { type: string, maxLength: 200 }
Quote:
type: object
required: [listing_id, start_date, end_date, days, available, daily_price_cents, subtotal_cents, service_fee_cents, total_price_cents, deposit_cents, currency, cancellation_policy]
properties:
listing_id: { type: string, format: uuid }
start_date: { type: string, format: date }
end_date: { type: string, format: date }
days: { type: integer }
available: { type: boolean }
daily_price_cents: { type: integer }
subtotal_cents: { type: integer }
service_fee_cents: { type: integer }
total_price_cents: { type: integer }
deposit_cents: { type: integer, description: Authorized ~24h before pickup and released on return }
currency: { $ref: '#/components/schemas/Currency' }
cancellation_policy: { $ref: '#/components/schemas/CancellationPolicy' }
BookingStatus:
type: string
enum: [pending, confirmed, active, completed, cancelled, disputed]
PaymentStatus:
type: string
enum: [requires_action, authorized, captured, refunded, partially_refunded, failed]
BookingCreate:
type: object
required: [listing_id, start_date, end_date]
additionalProperties: false
properties:
listing_id: { type: string, format: uuid }
start_date: { type: string, format: date }
end_date: { type: string, format: date }
message: { type: string, maxLength: 1000, description: Optional note to the owner }
expected_total_price_cents:
type: integer
minimum: 0
description: Total the renter saw in the quote. If the price changed, the request fails with 409 price_changed.
Booking:
type: object
required: [id, listing, renter, owner, start_date, end_date, days, status, total_price_cents, service_fee_cents, deposit_cents, currency, allowed_actions, created_at, updated_at]
properties:
id: { type: string, format: uuid }
listing:
type: object
properties:
id: { type: string, format: uuid }
title: { type: string }
cover_photo_url: { type: string, format: uri, nullable: true }
renter: { $ref: '#/components/schemas/UserSummary' }
owner: { $ref: '#/components/schemas/UserSummary' }
start_date: { type: string, format: date }
end_date: { type: string, format: date }
days: { type: integer }
status: { $ref: '#/components/schemas/BookingStatus' }
total_price_cents: { type: integer }
service_fee_cents: { type: integer }
deposit_cents: { type: integer }
refund_cents: { type: integer, nullable: true }
currency: { $ref: '#/components/schemas/Currency' }
payment:
type: object
nullable: true
properties:
id: { type: string, format: uuid }
status: { $ref: '#/components/schemas/PaymentStatus' }
amount_cents: { type: integer }
cancellation_reason: { type: string, nullable: true }
expires_at:
type: string
format: date-time
nullable: true
description: When a pending booking auto-expires
allowed_actions:
type: array
description: Actions the caller may perform now
items: { type: string, enum: [confirm, decline, cancel, start, complete, dispute, review] }
created_at: { type: string, format: date-time }
updated_at: { type: string, format: date-time }
BookingCreated:
allOf:
- $ref: '#/components/schemas/Booking'
- type: object
required: [payment_client_secret]
properties:
payment_client_secret:
type: string
description: Stripe PaymentIntent client secret used to confirm payment client-side (3DS supported)
BookingPage:
type: object
required: [data, page]
properties:
data:
type: array
items: { $ref: '#/components/schemas/Booking' }
page: { $ref: '#/components/schemas/PageInfo' }
ReasonRequest:
type: object
required: [reason]
additionalProperties: false
properties:
reason: { type: string, minLength: 3, maxLength: 500 }
DisputeCreate:
type: object
required: [category, description]
additionalProperties: false
properties:
category: { type: string, enum: [damage, not_as_described, not_returned, late_return, other] }
description: { type: string, minLength: 20, maxLength: 4000 }
claim_cents: { type: integer, minimum: 0, description: Amount claimed against the deposit (owner) }
evidence_urls:
type: array
maxItems: 10
items: { type: string, format: uri }
DisputeResolution:
type: object
required: [deposit_to_owner_cents, resolution_note]
additionalProperties: false
properties:
deposit_to_owner_cents: { type: integer, minimum: 0 }
additional_refund_to_renter_cents: { type: integer, minimum: 0, default: 0 }
resolution_note: { type: string, minLength: 10, maxLength: 4000 }
ReviewCreate:
type: object
required: [rating]
additionalProperties: false
properties:
rating: { type: integer, minimum: 1, maximum: 5 }
comment: { type: string, maxLength: 2000 }
Review:
type: object
required: [id, booking_id, author, target_type, target_id, rating, created_at]
properties:
id: { type: string, format: uuid }
booking_id: { type: string, format: uuid }
author: { $ref: '#/components/schemas/UserSummary' }
target_type: { type: string, enum: [listing, user] }
target_id: { type: string, format: uuid }
rating: { type: integer, minimum: 1, maximum: 5 }
comment: { type: string, nullable: true }
published_at: { type: string, format: date-time, nullable: true }
created_at: { type: string, format: date-time }
ReviewPage:
type: object
required: [data, page]
properties:
data:
type: array
items: { $ref: '#/components/schemas/Review' }
page: { $ref: '#/components/schemas/PageInfo' }
ConversationCreate:
type: object
required: [listing_id, body]
additionalProperties: false
properties:
listing_id: { type: string, format: uuid }
body: { type: string, minLength: 1, maxLength: 2000 }
Conversation:
type: object
required: [id, participants, unread_count, created_at]
properties:
id: { type: string, format: uuid }
listing:
type: object
nullable: true
properties:
id: { type: string, format: uuid }
title: { type: string }
participants:
type: array
items: { $ref: '#/components/schemas/UserSummary' }
last_message:
allOf:
- $ref: '#/components/schemas/Message'
nullable: true
unread_count: { type: integer }
created_at: { type: string, format: date-time }
ConversationPage:
type: object
required: [data, page]
properties:
data:
type: array
items: { $ref: '#/components/schemas/Conversation' }
page: { $ref: '#/components/schemas/PageInfo' }
MessageCreate:
type: object
required: [body]
additionalProperties: false
properties:
body: { type: string, minLength: 1, maxLength: 2000 }
Message:
type: object
required: [id, conversation_id, sender_id, body, created_at]
properties:
id: { type: string, format: uuid }
conversation_id: { type: string, format: uuid }
sender_id: { type: string, format: uuid }
body: { type: string }
read_at: { type: string, format: date-time, nullable: true }
created_at: { type: string, format: date-time }
MessagePage:
type: object
required: [data, page]
properties:
data:
type: array
items: { $ref: '#/components/schemas/Message' }
page: { $ref: '#/components/schemas/PageInfo' }
Payout:
type: object
required: [id, amount_cents, currency, status, period_start, period_end, payment_count, created_at]
properties:
id: { type: string, format: uuid }
amount_cents: { type: integer }
currency: { $ref: '#/components/schemas/Currency' }
status: { type: string, enum: [pending, paid, failed] }
period_start: { type: string, format: date }
period_end: { type: string, format: date }
payment_count: { type: integer }
created_at: { type: string, format: date-time }
PayoutPage:
type: object
required: [data, page]
properties:
data:
type: array
items: { $ref: '#/components/schemas/Payout' }
page: { $ref: '#/components/schemas/PageInfo' }
4. Implementation Skeleton (NestJS 10 + TypeORM)
Project layout
src/
├── main.ts
├── app.module.ts
├── config/ (typed config: db, redis, auth0, stripe, pricing)
├── common/
│ ├── errors/ (domain.error.ts, problem-details.filter.ts, validation.ts)
│ ├── idempotency/ (idempotent.decorator.ts, idempotency.interceptor.ts)
│ ├── pagination/ (cursor.ts)
│ ├── throttling/ (user-throttler.guard.ts)
│ ├── audit/ (audit.service.ts)
│ └── outbox/ (outbox.service.ts, outbox.relay.ts)
├── auth/ (jwt.strategy.ts, jwt-auth.guard.ts, scopes.guard.ts, decorators.ts)
├── users/ categories/ listings/ availability/ bookings/
├── payments/ (payments.service.ts, stripe-webhook.controller.ts, stripe-events.processor.ts)
├── payouts/ reviews/ messaging/ admin/
└── migrations/
4.1 Bootstrap: main.ts
// src/main.ts
import { ValidationPipe, VersioningType } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { ConfigService } from '@nestjs/config';
import helmet from 'helmet';
import { Logger } from 'nestjs-pino';
import { AppModule } from './app.module';
import { validationExceptionFactory } from './common/errors/validation';
async function bootstrap(): Promise<void> {
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
rawBody: true, // needed for Stripe signature verification
bufferLogs: true,
});
const config = app.get(ConfigService);
app.useLogger(app.get(Logger));
app.set('trust proxy', 1); // behind ALB/CDN: correct req.ip for rate limiting
app.useBodyParser('json', { limit: '100kb' });
app.use(helmet({ contentSecurityPolicy: false })); // JSON API; CSP lives on the web app
app.setGlobalPrefix('api');
app.enableVersioning({ type: VersioningType.URI, defaultVersion: '1' }); // → /api/v1/...
app.enableCors({
origin: config.getOrThrow<string>('CORS_ALLOWED_ORIGINS').split(','), // explicit allowlist, never '*'
methods: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Authorization', 'Content-Type', 'Idempotency-Key', 'If-Match', 'X-Request-Id'],
exposedHeaders: ['ETag', 'Location', 'Retry-After', 'X-Request-Id', 'Idempotent-Replayed',
'X-RateLimit-Limit', 'X-RateLimit-Remaining', 'X-RateLimit-Reset'],
credentials: false, // bearer tokens, no cookies → no CSRF surface on the API
maxAge: 600,
});
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true, // unknown fields/params → error (typo protection, mass-assignment protection)
transform: true,
transformOptions: { enableImplicitConversion: false },
exceptionFactory: validationExceptionFactory,
}),
);
app.enableShutdownHooks(); // drain connections on SIGTERM during rolling deploys
await app.listen(config.get<number>('PORT', 3000), '0.0.0.0');
}
void bootstrap();
4.2 Module wiring: app.module.ts
// src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ThrottlerModule } from '@nestjs/throttler';
import { ThrottlerStorageRedisService } from '@nest-lab/throttler-storage-redis';
import { RedisModule } from '@nestjs-modules/ioredis';
import { LoggerModule } from 'nestjs-pino';
import { SnakeNamingStrategy } from 'typeorm-naming-strategies';
import { randomUUID } from 'node:crypto';
import Redis from 'ioredis';
import { AuthModule } from './auth/auth.module';
import { JwtAuthGuard } from './auth/jwt-auth.guard';
import { ScopesGuard } from './auth/scopes.guard';
import { UserThrottlerGuard } from './common/throttling/user-throttler.guard';
import { ProblemDetailsFilter } from './common/errors/problem-details.filter';
import { IdempotencyInterceptor } from './common/idempotency/idempotency.interceptor';
import { ListingsModule } from './listings/listings.module';
import { BookingsModule } from './bookings/bookings.module';
import { PaymentsModule } from './payments/payments.module';
// ...other feature modules
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true, cache: true }),
LoggerModule.forRoot({
pinoHttp: {
genReqId: (req, res) => {
const incoming = req.headers['x-request-id'];
const id = typeof incoming === 'string' && /^[\w-]{8,64}$/.test(incoming) ? incoming : randomUUID();
res.setHeader('X-Request-Id', id);
return id;
},
redact: ['req.headers.authorization', 'req.headers.cookie', 'req.body.phone', 'req.body.email'],
customProps: (req) => ({ userId: (req as any).user?.userId }),
},
}),
TypeOrmModule.forRootAsync({
inject: [ConfigService],
useFactory: (cfg: ConfigService) => ({
type: 'postgres',
namingStrategy: new SnakeNamingStrategy(),
autoLoadEntities: true,
synchronize: false, // migrations only
migrationsRun: false, // run as a separate deploy step
replication: {
master: { url: cfg.getOrThrow('DATABASE_URL') }, // → PgBouncer (primary)
slaves: [{ url: cfg.getOrThrow('DATABASE_REPLICA_URL') }], // → PgBouncer (replicas)
},
extra: {
max: cfg.get<number>('DB_POOL_MAX', 15), // per pod; see sizing in §5
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 2_000, // fail fast instead of queueing under burst
statement_timeout: 5_000, // guard against runaway queries
application_name: 'gearloop-api',
},
ssl: { rejectUnauthorized: true },
}),
}),
RedisModule.forRootAsync({
inject: [ConfigService],
useFactory: (cfg: ConfigService) => ({ type: 'single', url: cfg.getOrThrow('REDIS_URL') }),
}),
ThrottlerModule.forRootAsync({
inject: [ConfigService],
useFactory: (cfg: ConfigService) => ({
throttlers: [
{ name: 'burst', ttl: 1_000, limit: 20 }, // per user/IP per second
{ name: 'default', ttl: 60_000, limit: 300 }, // per user/IP per minute
],
storage: new ThrottlerStorageRedisService(new Redis(cfg.getOrThrow('REDIS_URL'))),
}),
}),
AuthModule,
ListingsModule,
BookingsModule,
PaymentsModule,
],
providers: [
// Guards run in registration order: authenticate → authorize → rate limit (keyed by user)
{ provide: APP_GUARD, useClass: JwtAuthGuard },
{ provide: APP_GUARD, useClass: ScopesGuard },
{ provide: APP_GUARD, useClass: UserThrottlerGuard },
{ provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor },
{ provide: APP_FILTER, useClass: ProblemDetailsFilter },
],
})
export class AppModule {}
4.3 Structured errors (RFC 7807)
// src/common/errors/domain.error.ts
import { HttpStatus } from '@nestjs/common';
export interface FieldError { field: string; message: string; code?: string }
export interface DomainErrorExtras {
detail?: string;
errors?: FieldError[];
headers?: Record<string, string>;
}
export class DomainError extends Error {
constructor(
readonly status: HttpStatus,
readonly code: string,
message: string,
readonly extras: DomainErrorExtras = {},
) {
super(message);
this.name = 'DomainError';
}
}
export const Errors = {
unauthorized: () =>
new DomainError(HttpStatus.UNAUTHORIZED, 'unauthorized', 'Missing or invalid access token', {
headers: { 'WWW-Authenticate': 'Bearer error="invalid_token"' },
}),
insufficientScope: (scopes: string[]) =>
new DomainError(HttpStatus.FORBIDDEN, 'insufficient_scope', 'Token lacks required scope', {
detail: `Required: ${scopes.join(' ')}`,
headers: { 'WWW-Authenticate': `Bearer error="insufficient_scope", scope="${scopes.join(' ')}"` },
}),
accountSuspended: () =>
new DomainError(HttpStatus.FORBIDDEN, 'account_suspended', 'This account is suspended'),
notFound: (resource: string) =>
new DomainError(HttpStatus.NOT_FOUND, 'not_found', `${resource} not found`),
forbiddenAction: (detail: string) =>
new DomainError(HttpStatus.FORBIDDEN, 'action_not_permitted', 'You cannot perform this action', { detail }),
datesUnavailable: () =>
new DomainError(HttpStatus.CONFLICT, 'dates_unavailable', 'The requested dates are not available'),
invalidTransition: (from: string, action: string) =>
new DomainError(HttpStatus.CONFLICT, 'invalid_state_transition', `Cannot ${action} a booking that is ${from}`),
concurrentModification: () =>
new DomainError(HttpStatus.CONFLICT, 'concurrent_modification', 'Resource changed concurrently; refetch and retry'),
priceChanged: (expected: number, actual: number) =>
new DomainError(HttpStatus.CONFLICT, 'price_changed', 'The price has changed since your quote', {
detail: `Expected ${expected}, current total is ${actual}`,
}),
versionMismatch: () =>
new DomainError(HttpStatus.PRECONDITION_FAILED, 'version_mismatch', 'If-Match does not match the current version'),
validation: (errors: FieldError[]) =>
new DomainError(HttpStatus.UNPROCESSABLE_ENTITY, 'validation_failed', 'Request validation failed', { errors }),
paymentProvider: () =>
new DomainError(HttpStatus.BAD_GATEWAY, 'payment_provider_error', 'Payment provider unavailable; retry with the same Idempotency-Key'),
};
// src/common/errors/validation.ts
import { ValidationError } from 'class-validator';
import { Errors, FieldError } from './domain.error';
function flatten(errors: ValidationError[], parent = ''): FieldError[] {
return errors.flatMap((e) => {
const field = parent ? `${parent}.${e.property}` : e.property;
const own = Object.entries(e.constraints ?? {}).map(([code, message]) => ({ field, message, code }));
return [...own, ...flatten(e.children ?? [], field)];
});
}
export const validationExceptionFactory = (errors: ValidationError[]) => Errors.validation(flatten(errors));
// src/common/errors/problem-details.filter.ts
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common';
import type { Request, Response } from 'express';
import { QueryFailedError } from 'typeorm';
import { DomainError, Errors } from './domain.error';
const STATUS_CODES: Record<number, string> = {
400: 'bad_request', 401: 'unauthorized', 403: 'forbidden', 404: 'not_found',
405: 'method_not_allowed', 413: 'payload_too_large', 415: 'unsupported_media_type', 429: 'rate_limited',
};
/** Map known Postgres constraint violations to domain errors by constraint name, never by message text. */
const CONSTRAINT_MAP: Record<string, () => DomainError> = {
availability_no_overlap: Errors.datesUnavailable,
uq_reviews_booking_author: () => new DomainError(409, 'already_reviewed', 'You already reviewed this booking'),
};
@Catch()
export class ProblemDetailsFilter implements ExceptionFilter {
private readonly logger = new Logger(ProblemDetailsFilter.name);
catch(exception: unknown, host: ArgumentsHost): void {
const http = host.switchToHttp();
const req = http.getRequest<Request & { id?: string }>();
const res = http.getResponse<Response>();
const err = this.normalize(exception);
if (err.status >= 500) {
this.logger.error({ err: exception, requestId: req.id }, 'Unhandled error');
}
for (const [k, v] of Object.entries(err.extras.headers ?? {})) res.setHeader(k, v);
if (err.status === HttpStatus.TOO_MANY_REQUESTS && !res.getHeader('Retry-After')) {
res.setHeader('Retry-After', '1');
}
res
.status(err.status)
.type('application/problem+json')
.json({
type: `https://docs.gearloop.com/errors/${err.code}`,
title: err.message,
status: err.status,
code: err.code,
detail: err.extras.detail,
instance: req.originalUrl.split('?')[0],
request_id: req.id,
errors: err.extras.errors,
});
}
private normalize(e: unknown): DomainError {
if (e instanceof DomainError) return e;
if (e instanceof HttpException) {
const status = e.getStatus();
// Never echo framework internals for 5xx
const message = status >= 500 ? 'An unexpected error occurred' : e.message;
return new DomainError(status, STATUS_CODES[status] ?? 'http_error', message);
}
if (e instanceof QueryFailedError) {
const constraint = (e.driverError as { constraint?: string }).constraint;
const mapped = constraint ? CONSTRAINT_MAP[constraint] : undefined;
if (mapped) return mapped();
if ((e.driverError as { code?: string }).code === '40001') return Errors.concurrentModification();
}
return new DomainError(HttpStatus.INTERNAL_SERVER_ERROR, 'internal_error', 'An unexpected error occurred');
}
}
4.4 Authentication and authorization (Auth0)
// src/auth/decorators.ts
import { createParamDecorator, ExecutionContext, SetMetadata } from '@nestjs/common';
export type Scope =
| 'profile:write' | 'bookings:write' | 'bookings:manage' | 'listings:write'
| 'reviews:write' | 'messages:write' | 'payouts:read' | 'admin:all';
export interface AuthPrincipal {
sub: string; // Auth0 subject
userId: string; // local users.id
roles: Array<'renter' | 'owner' | 'admin'>;
permissions: Scope[];
}
export const SCOPES_KEY = 'gearloop:scopes';
export const IS_PUBLIC_KEY = 'gearloop:public';
/** Endpoint requires ALL listed scopes (Auth0 RBAC `permissions` claim). */
export const RequireScopes = (...scopes: Scope[]) => SetMetadata(SCOPES_KEY, scopes);
/** No token required. If a token is sent, it is still validated (so owners see their drafts). */
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
export const CurrentUser = createParamDecorator(
(_: unknown, ctx: ExecutionContext): AuthPrincipal | undefined => ctx.switchToHttp().getRequest().user,
);
// src/auth/jwt.strategy.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { passportJwtSecret } from 'jwks-rsa';
import { UsersService } from '../users/users.service';
import { Errors } from '../common/errors/domain.error';
import type { AuthPrincipal, Scope } from './decorators';
interface Auth0AccessToken {
sub: string;
permissions?: Scope[];
'https://gearloop.com/email'?: string; // namespaced custom claim added by an Auth0 Action
'https://gearloop.com/email_verified'?: boolean;
}
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(config: ConfigService, private readonly users: UsersService) {
const domain = config.getOrThrow<string>('AUTH0_DOMAIN');
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKeyProvider: passportJwtSecret({
jwksUri: `https://${domain}/.well-known/jwks.json`,
cache: true, // keys cached in memory; refetched on unknown `kid` (key rotation)
cacheMaxAge: 10 * 60 * 1000,
rateLimit: true,
jwksRequestsPerMinute: 10,
}),
audience: config.getOrThrow<string>('AUTH0_AUDIENCE'), // e.g. https://api.gearloop.com
issuer: `https://${domain}/`,
algorithms: ['RS256'], // pin the algorithm: rejects `none` and HS256 key confusion
jsonWebTokenOptions: { clockTolerance: 30 } as never,
});
}
/** Runs after signature/exp/aud/iss validation. Maps the token to a local user (JIT-provisioned, Redis-cached for 60s). */
async validate(payload: Auth0AccessToken): Promise<AuthPrincipal> {
const user = await this.users.resolveByAuth0Sub(payload.sub, {
email: payload['https://gearloop.com/email'],
emailVerified: payload['https://gearloop.com/email_verified'] ?? false,
});
// 15-minute tokens can't be revoked instantly, so a suspension check on every request closes the gap.
if (user.suspendedAt) throw Errors.accountSuspended();
return { sub: payload.sub, userId: user.id, roles: user.roles, permissions: payload.permissions ?? [] };
}
}
// src/auth/jwt-auth.guard.ts
import { ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import type { Request } from 'express';
import { IS_PUBLIC_KEY } from './decorators';
import { Errors } from '../common/errors/domain.error';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
constructor(private readonly reflector: Reflector) { super(); }
canActivate(ctx: ExecutionContext) {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [ctx.getHandler(), ctx.getClass()]);
const req = ctx.switchToHttp().getRequest<Request>();
if (isPublic && !req.headers.authorization) return true; // anonymous access allowed
return super.canActivate(ctx); // token present → must be valid
}
handleRequest<T>(err: unknown, user: T | false): T {
if (err instanceof Error && err.name === 'DomainError') throw err; // e.g. account_suspended
if (err || !user) throw Errors.unauthorized();
return user;
}
}
// src/auth/scopes.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthPrincipal, Scope, SCOPES_KEY } from './decorators';
import { Errors } from '../common/errors/domain.error';
@Injectable()
export class ScopesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(ctx: ExecutionContext): boolean {
const required = this.reflector.getAllAndOverride<Scope[]>(SCOPES_KEY, [ctx.getHandler(), ctx.getClass()]);
if (!required?.length) return true;
const principal = ctx.switchToHttp().getRequest().user as AuthPrincipal | undefined;
if (!principal) throw Errors.unauthorized();
const missing = required.filter((s) => !principal.permissions.includes(s));
if (missing.length) throw Errors.insufficientScope(missing);
return true; // resource-level ownership is enforced in services
}
}
// src/common/throttling/user-throttler.guard.ts
import { Injectable } from '@nestjs/common';
import { ThrottlerGuard } from '@nestjs/throttler';
/** Rate limit per authenticated user, falling back to client IP for anonymous traffic. */
@Injectable()
export class UserThrottlerGuard extends ThrottlerGuard {
protected async getTracker(req: Record<string, any>): Promise<string> {
return req.user?.userId ? `u:${req.user.userId}` : `ip:${req.ip}`;
}
}
4.5 Idempotency interceptor
// src/common/idempotency/idempotent.decorator.ts
import { SetMetadata } from '@nestjs/common';
export const IDEMPOTENT_KEY = 'gearloop:idempotent';
export const Idempotent = () => SetMetadata(IDEMPOTENT_KEY, true);
// src/common/idempotency/idempotency.interceptor.ts
import { CallHandler, ExecutionContext, HttpStatus, Injectable, Logger, NestInterceptor } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { InjectRedis } from '@nestjs-modules/ioredis';
import type { Request, Response } from 'express';
import Redis from 'ioredis';
import { createHash } from 'node:crypto';
import { Observable, of, tap } from 'rxjs';
import { IDEMPOTENT_KEY } from './idempotent.decorator';
import { DomainError } from '../errors/domain.error';
import type { AuthPrincipal } from '../../auth/decorators';
type Stored =
| { state: 'in_progress'; fingerprint: string }
| { state: 'completed'; fingerprint: string; body: unknown };
const KEY_PATTERN = /^[A-Za-z0-9_-]{8,255}$/;
const LOCK_TTL_S = 60;
const RESULT_TTL_S = 24 * 60 * 60;
/**
* Stripe-style idempotency:
* - same key + same body → replay the stored success response
* - same key + different body → 422
* - concurrent duplicate → 409 with Retry-After
* Failures release the key so the client can retry.
* Database constraints and Stripe idempotency keys provide a second line of defense if Redis loses data.
*/
@Injectable()
export class IdempotencyInterceptor implements NestInterceptor {
private readonly logger = new Logger(IdempotencyInterceptor.name);
constructor(private readonly reflector: Reflector, @InjectRedis() private readonly redis: Redis) {}
async intercept(ctx: ExecutionContext, next: CallHandler): Promise<Observable<unknown>> {
if (!this.reflector.get<boolean>(IDEMPOTENT_KEY, ctx.getHandler())) return next.handle();
const req = ctx.switchToHttp().getRequest<Request & { user?: AuthPrincipal }>();
const res = ctx.switchToHttp().getResponse<Response>();
const key = req.header('idempotency-key');
if (!key || !KEY_PATTERN.test(key)) {
throw new DomainError(HttpStatus.BAD_REQUEST, 'idempotency_key_required',
'A valid Idempotency-Key header is required for this operation');
}
const fingerprint = createHash('sha256')
.update(`${req.method}:${req.originalUrl}:${JSON.stringify(req.body ?? {})}`)
.digest('hex');
const redisKey = `idem:${req.user?.userId ?? 'anon'}:${key}`;
const acquired = await this.redis.set(
redisKey, JSON.stringify({ state: 'in_progress', fingerprint } satisfies Stored), 'EX', LOCK_TTL_S, 'NX');
if (!acquired) {
const raw = await this.redis.get(redisKey);
const stored = raw ? (JSON.parse(raw) as Stored) : null;
if (stored && stored.fingerprint !== fingerprint) {
throw new DomainError(HttpStatus.UNPROCESSABLE_ENTITY, 'idempotency_key_reused',
'Idempotency-Key was already used with a different request');
}
if (!stored || stored.state === 'in_progress') {
throw new DomainError(HttpStatus.CONFLICT, 'idempotency_in_progress',
'A request with this Idempotency-Key is in progress', { headers: { 'Retry-After': '1' } });
}
res.setHeader('Idempotent-Replayed', 'true');
return of(stored.body);
}
return next.handle().pipe(
tap({
next: (body) => {
const record: Stored = { state: 'completed', fingerprint, body };
this.redis.set(redisKey, JSON.stringify(record), 'EX', RESULT_TTL_S)
.catch((err) => this.logger.warn({ err }, 'Failed to persist idempotent response'));
},
error: () => { void this.redis.del(redisKey); },
}),
);
}
}
4.6 Cursor pagination helper
// src/common/pagination/cursor.ts
import { Errors } from '../errors/domain.error';
export type CursorValue = string | number;
export interface Page<T> { data: T[]; page: { next_cursor: string | null; has_more: boolean; limit: number } }
export const encodeCursor = (values: CursorValue[]): string =>
Buffer.from(JSON.stringify(values), 'utf8').toString('base64url');
export function decodeCursor(cursor: string | undefined, arity: number): CursorValue[] | undefined {
if (!cursor) return undefined;
try {
const v = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
if (Array.isArray(v) && v.length === arity && v.every((x) => ['string', 'number'].includes(typeof x))) return v;
} catch { /* fall through */ }
throw Errors.validation([{ field: 'cursor', message: 'Invalid cursor', code: 'invalid_cursor' }]);
}
/** Fetch limit+1 rows; the extra row only signals has_more. */
export function toPage<R, T>(rows: R[], limit: number, map: (r: R) => T, cursorOf: (r: R) => CursorValue[]): Page<T> {
const hasMore = rows.length > limit;
const slice = hasMore ? rows.slice(0, limit) : rows;
return {
data: slice.map(map),
page: { next_cursor: hasMore ? encodeCursor(cursorOf(slice[slice.length - 1])) : null, has_more: hasMore, limit },
};
}
4.7 Entities
// src/listings/listing.entity.ts
import {
Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn, UpdateDateColumn, VersionColumn,
} from 'typeorm';
import type { Point } from 'geojson';
import { User } from '../users/user.entity';
import { Category } from '../categories/category.entity';
export enum ListingStatus { Draft = 'draft', Published = 'published', Paused = 'paused', Archived = 'archived' }
export enum ListingCondition { New = 'new', Good = 'good', Fair = 'fair' }
export enum CancellationPolicy { Flexible = 'flexible', Moderate = 'moderate', Strict = 'strict' }
const numeric = { to: (v?: number | null) => v, from: (v: string | null) => (v === null ? null : Number(v)) };
@Entity('listings')
export class Listing {
@PrimaryGeneratedColumn('uuid') id!: string;
@Column('uuid') ownerId!: string;
@ManyToOne(() => User, { onDelete: 'RESTRICT' }) @JoinColumn({ name: 'owner_id' }) owner!: User;
@Column('uuid') categoryId!: string;
@ManyToOne(() => Category, { onDelete: 'RESTRICT' }) @JoinColumn({ name: 'category_id' }) category!: Category;
@Column({ length: 120 }) title!: string;
@Column('text') description!: string;
@Column('integer') dailyPriceCents!: number;
@Column({ type: 'char', length: 3 }) currency!: string;
@Column('integer', { default: 0 }) depositCents!: number;
@Column({ type: 'enum', enum: ListingCondition }) condition!: ListingCondition;
@Column({ type: 'enum', enum: CancellationPolicy }) cancellationPolicy!: CancellationPolicy;
@Column({ type: 'enum', enum: ListingStatus, default: ListingStatus.Draft }) status!: ListingStatus;
/** Exact location (private). Public responses use a ~500 m fuzzed point. */
@Column({ type: 'geography', spatialFeatureType: 'Point', srid: 4326 }) geog!: Point;
@Column({ type: 'geography', spatialFeatureType: 'Point', srid: 4326 }) publicGeog!: Point;
@Column({ length: 100 }) city!: string;
@Column({ length: 100 }) region!: string;
@Column({ type: 'char', length: 2 }) country!: string;
@Column({ length: 64 }) timezone!: string;
@Column('text', { array: true, default: () => "'{}'" }) photos!: string[];
@Column('numeric', { precision: 3, scale: 2, nullable: true, transformer: numeric }) ratingAvg!: number | null;
@Column('integer', { default: 0 }) ratingCount!: number;
@VersionColumn() version!: number;
@CreateDateColumn({ type: 'timestamptz' }) createdAt!: Date;
@UpdateDateColumn({ type: 'timestamptz' }) updatedAt!: Date;
}
// src/bookings/booking.entity.ts
import { Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn, UpdateDateColumn, VersionColumn } from 'typeorm';
import { Listing } from '../listings/listing.entity';
import { User } from '../users/user.entity';
export enum BookingStatus {
Pending = 'pending', Confirmed = 'confirmed', Active = 'active',
Completed = 'completed', Cancelled = 'cancelled', Disputed = 'disputed',
}
@Entity('bookings')
export class Booking {
@PrimaryGeneratedColumn('uuid') id!: string;
@Column('uuid') listingId!: string;
@ManyToOne(() => Listing) @JoinColumn({ name: 'listing_id' }) listing!: Listing;
@Column('uuid') renterId!: string;
@ManyToOne(() => User) @JoinColumn({ name: 'renter_id' }) renter!: User;
/** Denormalized from listing so owner queries don't need a join. Immutable after creation. */
@Column('uuid') ownerId!: string;
@ManyToOne(() => User) @JoinColumn({ name: 'owner_id' }) owner!: User;
@Column('date') startDate!: string; // 'YYYY-MM-DD', inclusive
@Column('date') endDate!: string; // 'YYYY-MM-DD', exclusive (return day)
@Column({ type: 'enum', enum: BookingStatus, default: BookingStatus.Pending }) status!: BookingStatus;
// Price snapshot at booking time: later listing edits never change existing bookings
@Column('integer') dailyPriceCents!: number;
@Column('integer') totalPriceCents!: number;
@Column('integer') serviceFeeCents!: number;
@Column('integer') depositCents!: number;
@Column({ type: 'char', length: 3 }) currency!: string;
@Column({ type: 'varchar', length: 16 }) cancellationPolicy!: string;
@Column('integer', { nullable: true }) refundCents!: number | null;
@Column('uuid', { nullable: true }) paymentId!: string | null;
@Column('text', { nullable: true }) cancellationReason!: string | null;
@Column('text', { nullable: true }) renterMessage!: string | null;
@Column({ type: 'timestamptz', nullable: true }) expiresAt!: Date | null;
@Column({ type: 'timestamptz', nullable: true }) completedAt!: Date | null;
@VersionColumn() version!: number;
@CreateDateColumn({ type: 'timestamptz' }) createdAt!: Date;
@UpdateDateColumn({ type: 'timestamptz' }) updatedAt!: Date;
}
// src/availability/availability-slot.entity.ts
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn } from 'typeorm';
export enum SlotKind { Blocked = 'blocked', Booked = 'booked' }
/** Single source of truth for occupied date ranges. Overlap is prevented by an exclusion constraint (see migration). */
@Entity('availability_slots')
export class AvailabilitySlot {
@PrimaryGeneratedColumn('uuid') id!: string;
@Column('uuid') listingId!: string;
@Column('date') startDate!: string;
@Column('date') endDate!: string;
@Column({ type: 'enum', enum: SlotKind }) kind!: SlotKind;
@Column('uuid', { nullable: true, unique: true }) bookingId!: string | null;
@Column('text', { nullable: true }) note!: string | null;
@CreateDateColumn({ type: 'timestamptz' }) createdAt!: Date;
}
4.8 Listings: search with PostGIS, keyset pagination and optimistic concurrency
// src/listings/dto/search-listings.query.ts
import { Transform, Type } from 'class-transformer';
import { IsEnum, IsIn, IsInt, IsISO8601, IsLatitude, IsLongitude, IsOptional, IsString, Matches, Max, MaxLength, Min } from 'class-validator';
import { ListingCondition } from '../listing.entity';
export const LISTING_SORTS = ['distance', 'price', '-price', '-created_at', '-rating'] as const;
export type ListingSort = (typeof LISTING_SORTS)[number];
export class SearchListingsQuery {
@IsOptional() @IsString() @MaxLength(100) q?: string;
@IsOptional() @Matches(/^[a-z0-9-]+$/) category?: string;
@IsOptional() @Type(() => Number) @IsLatitude() lat?: number;
@IsOptional() @Type(() => Number) @IsLongitude() lng?: number;
@IsOptional() @Type(() => Number) @IsInt() @Min(1) @Max(200) radius_km: number = 25;
@IsOptional() @IsISO8601({ strict: true, strictSeparator: true }) start_date?: string;
@IsOptional() @IsISO8601({ strict: true, strictSeparator: true }) end_date?: string;
@IsOptional() @Type(() => Number) @IsInt() @Min(0) min_price_cents?: number;
@IsOptional() @Type(() => Number) @IsInt() @Min(0) max_price_cents?: number;
@IsOptional()
@Transform(({ value }) => (typeof value === 'string' ? value.split(',') : value))
@IsEnum(ListingCondition, { each: true })
condition?: ListingCondition[];
@IsOptional() @IsIn(LISTING_SORTS) sort?: ListingSort;
@IsOptional() @IsString() @MaxLength(512) cursor?: string;
@IsOptional() @Type(() => Number) @IsInt() @Min(1) @Max(100) limit: number = 20;
}
// src/listings/dto/update-listing.dto.ts (create DTO is analogous with required fields)
import { Type } from 'class-transformer';
import { ArrayMaxSize, IsEnum, IsInt, IsOptional, IsString, IsUrl, IsUUID, Length, Max, Min, ValidateNested } from 'class-validator';
import { CancellationPolicy, ListingCondition } from '../listing.entity';
import { LocationInputDto } from './location-input.dto';
export class UpdateListingDto {
@IsOptional() @IsUUID('4') category_id?: string;
@IsOptional() @IsString() @Length(5, 120) title?: string;
@IsOptional() @IsString() @Length(20, 5000) description?: string;
@IsOptional() @IsInt() @Min(100) @Max(1_000_000) daily_price_cents?: number;
@IsOptional() @IsInt() @Min(0) @Max(500_000) deposit_cents?: number;
@IsOptional() @IsEnum(ListingCondition) condition?: ListingCondition;
@IsOptional() @IsEnum(CancellationPolicy) cancellation_policy?: CancellationPolicy;
@IsOptional() @ValidateNested() @Type(() => LocationInputDto) location?: LocationInputDto;
@IsOptional() @ArrayMaxSize(12)
@IsUrl({ protocols: ['https'], require_protocol: true, host_whitelist: ['img.gearloop.com'] }, { each: true })
photos?: string[]; // only our CDN: blocks hotlinking/SSRF via photo URLs
}
// src/listings/listings.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { InjectRedis } from '@nestjs-modules/ioredis';
import Redis from 'ioredis';
import { createHash } from 'node:crypto';
import { DataSource, Repository } from 'typeorm';
import { Listing, ListingStatus } from './listing.entity';
import { SearchListingsQuery, ListingSort } from './dto/search-listings.query';
import { UpdateListingDto } from './dto/update-listing.dto';
import { CategoriesService } from '../categories/categories.service';
import { decodeCursor, Page, toPage } from '../common/pagination/cursor';
import { Errors, FieldError } from '../common/errors/domain.error';
import type { AuthPrincipal } from '../auth/decorators';
import { ListingSummaryDto, toListingDto, ListingDto } from './listing.mapper';
import { AuditService } from '../common/audit/audit.service';
const POINT = 'ST_SetSRID(ST_MakePoint(:lng, :lat), 4326)::geography';
/** Whitelisted sort expressions; user input never reaches SQL directly. */
const SORTS: Record<ListingSort, { expr: string; dir: 'ASC' | 'DESC' }> = {
distance: { expr: `ST_Distance(l.geog, ${POINT})`, dir: 'ASC' },
price: { expr: 'l.daily_price_cents', dir: 'ASC' },
'-price': { expr: 'l.daily_price_cents', dir: 'DESC' },
'-created_at': { expr: 'l.created_at', dir: 'DESC' },
'-rating': { expr: 'COALESCE(l.rating_avg, 0)', dir: 'DESC' },
};
const SEARCH_CACHE_TTL_S = 30;
const MAX_RANGE_DAYS = 30;
@Injectable()
export class ListingsService {
constructor(
@InjectRepository(Listing) private readonly repo: Repository<Listing>,
private readonly dataSource: DataSource,
private readonly categories: CategoriesService,
private readonly audit: AuditService,
@InjectRedis() private readonly redis: Redis,
) {}
async search(q: SearchListingsQuery): Promise<Page<ListingSummaryDto>> {
this.assertSearchQuery(q);
const sortKey: ListingSort = q.sort ?? (q.lat !== undefined ? 'distance' : '-created_at');
const cacheKey = `search:v1:${createHash('sha1').update(JSON.stringify(this.normalizeForCache(q, sortKey))).digest('hex')}`;
const cached = await this.redis.get(cacheKey);
if (cached) return JSON.parse(cached) as Page<ListingSummaryDto>;
const sort = SORTS[sortKey];
// Query builder SELECTs use the read replica under TypeORM replication
const qb = this.repo
.createQueryBuilder('l')
.innerJoin('l.category', 'c')
.select([
'l.id AS id', 'l.title AS title', 'l.daily_price_cents AS daily_price_cents', 'l.currency AS currency',
'l.condition AS condition', 'l.city AS city', 'l.region AS region',
'ST_Y(l.public_geog::geometry) AS approx_lat', 'ST_X(l.public_geog::geometry) AS approx_lng',
'l.photos[1] AS cover_photo_url', 'c.slug AS category_slug',
'l.rating_avg AS rating_avg', 'l.rating_count AS rating_count',
])
.addSelect(sort.expr, 'sort_key')
.where('l.status = :status', { status: ListingStatus.Published });
if (q.lat !== undefined && q.lng !== undefined) {
qb.addSelect(`ST_Distance(l.geog, ${POINT})`, 'distance_m')
.andWhere(`ST_DWithin(l.geog, ${POINT}, :radiusM)`) // uses the GiST index
.setParameters({ lat: q.lat, lng: q.lng, radiusM: q.radius_km * 1000 });
}
if (q.category) {
const path = await this.categories.pathForSlug(q.category); // cached tree; throws 422 if unknown
qb.andWhere('(c.path = :cpath OR c.path LIKE :cprefix)', { cpath: path, cprefix: `${path}/%` });
}
if (q.q) qb.andWhere(`l.search_vector @@ websearch_to_tsquery('english', :q)`, { q: q.q });
if (q.min_price_cents !== undefined) qb.andWhere('l.daily_price_cents >= :minP', { minP: q.min_price_cents });
if (q.max_price_cents !== undefined) qb.andWhere('l.daily_price_cents <= :maxP', { maxP: q.max_price_cents });
if (q.condition?.length) qb.andWhere('l.condition IN (:...conds)', { conds: q.condition });
if (q.start_date && q.end_date) {
qb.andWhere(
`NOT EXISTS (SELECT 1 FROM availability_slots s
WHERE s.listing_id = l.id AND s.period && daterange(:sd::date, :ed::date, '[)'))`,
{ sd: q.start_date, ed: q.end_date },
);
}
const after = decodeCursor(q.cursor, 2);
if (after) {
qb.andWhere(`(${sort.expr}, l.id) ${sort.dir === 'ASC' ? '>' : '<'} (:cv, :cid)`, { cv: after[0], cid: after[1] });
}
const rows = await qb
.orderBy('sort_key', sort.dir)
.addOrderBy('id', sort.dir)
.limit(q.limit + 1)
.getRawMany<ListingSummaryDto & { sort_key: string | number }>();
const page = toPage(
rows, q.limit,
({ sort_key, ...r }) => ({
...r,
rating_avg: r.rating_avg === null ? null : Number(r.rating_avg),
distance_m: r.distance_m === undefined ? null : Math.round(Number(r.distance_m)),
}),
(r) => [r.sort_key instanceof Date ? r.sort_key.toISOString() : r.sort_key, r.id],
);
await this.redis.set(cacheKey, JSON.stringify(page), 'EX', SEARCH_CACHE_TTL_S);
return page;
}
async getVisible(id: string, principal?: AuthPrincipal): Promise<ListingDto> {
const cacheKey = `listing:v1:${id}`;
const cached = await this.redis.get(cacheKey);
if (cached) {
const dto = JSON.parse(cached) as ListingDto;
if (dto.status === ListingStatus.Published || dto.owner.id === principal?.userId) return dto;
}
const listing = await this.repo.findOne({ where: { id }, relations: { owner: true, category: true } });
const isOwner = !!listing && listing.ownerId === principal?.userId;
if (!listing || (listing.status !== ListingStatus.Published && !isOwner)) throw Errors.notFound('Listing');
const dto = toListingDto(listing, { exactLocation: isOwner });
if (listing.status === ListingStatus.Published && !isOwner) {
await this.redis.set(cacheKey, JSON.stringify(dto), 'EX', 300);
}
return dto;
}
async update(principal: AuthPrincipal, id: string, dto: UpdateListingDto, ifMatch?: string): Promise<ListingDto> {
// Primary connection: owner reads must see their own writes immediately
const listing = await this.dataSource.manager.findOne(Listing, { where: { id } });
if (!listing || listing.ownerId !== principal.userId) throw Errors.notFound('Listing'); // 404, not 403
if (listing.status === ListingStatus.Archived) throw Errors.forbiddenAction('Archived listings are read-only');
if (ifMatch && ifMatch !== `W/"${listing.version}"`) throw Errors.versionMismatch();
const changes: Record<string, unknown> = {};
if (dto.title !== undefined) changes.title = dto.title;
if (dto.description !== undefined) changes.description = dto.description;
if (dto.daily_price_cents !== undefined) changes.dailyPriceCents = dto.daily_price_cents;
if (dto.deposit_cents !== undefined) changes.depositCents = dto.deposit_cents;
if (dto.condition !== undefined) changes.condition = dto.condition;
if (dto.cancellation_policy !== undefined) changes.cancellationPolicy = dto.cancellation_policy;
if (dto.photos !== undefined) changes.photos = dto.photos;
if (dto.category_id !== undefined) {
await this.categories.assertLeafExists(dto.category_id);
changes.categoryId = dto.category_id;
}
if (dto.location) {
const { lat, lng, city, region, country } = dto.location;
Object.assign(changes, {
geog: () => `ST_SetSRID(ST_MakePoint(${Number(lng)}, ${Number(lat)}), 4326)::geography`,
publicGeog: () => `fuzz_point(ST_SetSRID(ST_MakePoint(${Number(lng)}, ${Number(lat)}), 4326)::geography, 500)`,
city, region, country,
timezone: await this.categories.timezoneFor(lat, lng), // tz lookup (e.g. geo-tz), not shown
});
}
// Compare-and-set on version: no lost updates between concurrent edits (e.g. web + mobile)
const result = await this.dataSource
.createQueryBuilder()
.update(Listing)
.set({ ...changes, version: () => 'version + 1' })
.where('id = :id AND version = :version', { id, version: listing.version })
.execute();
if (result.affected === 0) throw Errors.versionMismatch();
await Promise.all([
this.redis.del(`listing:v1:${id}`),
this.audit.record({ actorId: principal.userId, action: 'listing.updated', resource: `listing:${id}`, diff: dto }),
]);
return this.getVisible(id, principal);
}
private assertSearchQuery(q: SearchListingsQuery): void {
const errors: FieldError[] = [];
if ((q.lat === undefined) !== (q.lng === undefined)) {
errors.push({ field: 'lat', message: 'lat and lng must be provided together', code: 'paired_params' });
}
if (q.sort === 'distance' && q.lat === undefined) {
errors.push({ field: 'sort', message: 'distance sort requires lat and lng', code: 'requires_location' });
}
if ((q.start_date === undefined) !== (q.end_date === undefined)) {
errors.push({ field: 'start_date', message: 'start_date and end_date must be provided together', code: 'paired_params' });
} else if (q.start_date && q.end_date) {
const days = (Date.parse(q.end_date) - Date.parse(q.start_date)) / 86_400_000;
if (days < 1) errors.push({ field: 'end_date', message: 'end_date must be after start_date', code: 'invalid_range' });
if (days > MAX_RANGE_DAYS) errors.push({ field: 'end_date', message: `Max ${MAX_RANGE_DAYS} days`, code: 'range_too_long' });
}
if (q.min_price_cents !== undefined && q.max_price_cents !== undefined && q.min_price_cents > q.max_price_cents) {
errors.push({ field: 'min_price_cents', message: 'min must be <= max', code: 'invalid_range' });
}
if (errors.length) throw Errors.validation(errors);
}
/** Round coordinates to about 1 km so nearby searches share cache entries. */
private normalizeForCache(q: SearchListingsQuery, sort: ListingSort) {
return {
...q, sort,
lat: q.lat === undefined ? undefined : Math.round(q.lat * 100) / 100,
lng: q.lng === undefined ? undefined : Math.round(q.lng * 100) / 100,
condition: q.condition?.slice().sort(),
};
}
}
Cache key caveat. Rounding lat/lng for the cache key is only safe if the query also uses the rounded point. Set
q.lat/q.lngto the rounded values before building the query. Otherwise two users about 1 km apart could be served each other's distance values. (Cleaner alternative: snap to geohash-6 cell centers.)
// src/listings/listings.controller.ts
import { Body, Controller, Get, Headers, Param, ParseUUIDPipe, Patch, Query, Res } from '@nestjs/common';
import type { Response } from 'express';
import { ListingsService } from './listings.service';
import { SearchListingsQuery } from './dto/search-listings.query';
import { UpdateListingDto } from './dto/update-listing.dto';
import { CurrentUser, Public, RequireScopes, type AuthPrincipal } from '../auth/decorators';
import { Throttle } from '@nestjs/throttler';
@Controller({ path: 'listings', version: '1' })
export class ListingsController {
constructor(private readonly listings: ListingsService) {}
@Get()
@Public()
@Throttle({ default: { limit: 120, ttl: 60_000 } })
async search(@Query() query: SearchListingsQuery, @Res({ passthrough: true }) res: Response) {
res.setHeader('Cache-Control', 'public, max-age=30, stale-while-revalidate=60');
return this.listings.search(query);
}
@Get(':id')
@Public()
async get(
@Param('id', new ParseUUIDPipe({ version: '4' })) id: string,
@CurrentUser() user: AuthPrincipal | undefined,
@Res({ passthrough: true }) res: Response,
) {
const dto = await this.listings.getVisible(id, user);
res.setHeader('ETag', `W/"${dto.version}"`);
res.setHeader('Cache-Control', user ? 'private, no-cache' : 'public, max-age=60');
return dto;
}
@Patch(':id')
@RequireScopes('listings:write')
async update(
@Param('id', new ParseUUIDPipe({ version: '4' })) id: string,
@Body() dto: UpdateListingDto,
@Headers('if-match') ifMatch: string | undefined,
@CurrentUser() user: AuthPrincipal,
@Res({ passthrough: true }) res: Response,
) {
const updated = await this.listings.update(user, id, dto, ifMatch);
res.setHeader('ETag', `W/"${updated.version}"`);
return updated;
}
// POST /, DELETE /:id, POST /:id/publish, /:id/pause, /:id/photos follow the same pattern.
}
4.9 Bookings: state machine, pricing, creation and transitions
// src/bookings/booking-state-machine.ts
import { Booking, BookingStatus as S } from './booking.entity';
import { DomainError, Errors } from '../common/errors/domain.error';
export type BookingAction = 'confirm' | 'decline' | 'cancel' | 'start' | 'complete' | 'dispute';
export type Actor = 'renter' | 'owner' | 'admin';
interface TransitionContext { booking: Booking; paymentStatus?: string; today: string }
interface Rule {
from: S[];
to: S;
actors: Actor[];
requiresReason?: boolean;
guard?: (ctx: TransitionContext) => DomainError | null;
}
const DISPUTE_WINDOW_MS = 48 * 3600 * 1000;
export const BOOKING_TRANSITIONS: Record<BookingAction, Rule> = {
confirm: {
from: [S.Pending], to: S.Confirmed, actors: ['owner'],
guard: ({ paymentStatus }) =>
paymentStatus === 'authorized' ? null : Errors.forbiddenAction('Payment has not been authorized yet'),
},
decline: { from: [S.Pending], to: S.Cancelled, actors: ['owner'], requiresReason: true },
cancel: { from: [S.Pending, S.Confirmed], to: S.Cancelled, actors: ['renter', 'owner', 'admin'], requiresReason: true },
start: {
from: [S.Confirmed], to: S.Active, actors: ['owner'],
guard: ({ booking, today }) =>
addDays(booking.startDate, -1) <= today ? null : Errors.forbiddenAction('Handover is allowed from 1 day before start'),
},
complete: { from: [S.Active], to: S.Completed, actors: ['owner', 'admin'] },
dispute: {
from: [S.Active, S.Completed], to: S.Disputed, actors: ['renter', 'owner'], requiresReason: true,
guard: ({ booking }) =>
booking.status !== S.Completed || (booking.completedAt && Date.now() - booking.completedAt.getTime() <= DISPUTE_WINDOW_MS)
? null
: Errors.forbiddenAction('The dispute window (48h after completion) has closed'),
},
};
export function resolveActor(userId: string, isAdmin: boolean, b: Booking): Actor | null {
if (b.ownerId === userId) return 'owner';
if (b.renterId === userId) return 'renter';
return isAdmin ? 'admin' : null;
}
export function allowedActions(b: Booking, actor: Actor): BookingAction[] {
return (Object.keys(BOOKING_TRANSITIONS) as BookingAction[]).filter((a) => {
const r = BOOKING_TRANSITIONS[a];
return r.from.includes(b.status) && r.actors.includes(actor);
});
}
// --- date helpers (date-only, timezone-safe via UTC arithmetic) ---
export const daysBetween = (start: string, end: string) =>
Math.round((Date.parse(`${end}T00:00:00Z`) - Date.parse(`${start}T00:00:00Z`)) / 86_400_000);
export const addDays = (d: string, n: number) =>
new Date(Date.parse(`${d}T00:00:00Z`) + n * 86_400_000).toISOString().slice(0, 10);
export const todayIn = (timeZone: string) =>
new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date());
// --- refund policy (subtotal only; service fee refunded only on 100%) ---
export function refundFraction(policy: string, b: Booking, today: string, actor: Actor): number {
if (actor !== 'renter' || b.status === S.Pending) return 1; // owner/admin cancellations, pre-confirmation → full
const daysBefore = daysBetween(today, b.startDate);
const bookedWithin48h = Date.now() - b.createdAt.getTime() <= 48 * 3600 * 1000;
switch (policy) {
case 'flexible': return daysBefore >= 1 ? 1 : 0.5;
case 'moderate': return daysBefore >= 5 ? 1 : daysBefore >= 1 ? 0.5 : 0;
case 'strict': return daysBefore >= 14 || bookedWithin48h ? 1 : daysBefore >= 7 ? 0.5 : 0;
default: return 0;
}
}
// src/bookings/pricing.service.ts
import { Inject, Injectable } from '@nestjs/common';
import { ConfigType, registerAs } from '@nestjs/config';
import { Listing } from '../listings/listing.entity';
import { daysBetween } from './booking-state-machine';
export const pricingConfig = registerAs('pricing', () => ({
renterServiceFeeBps: Number(process.env.RENTER_SERVICE_FEE_BPS ?? 1200), // 12%
minServiceFeeCents: Number(process.env.MIN_SERVICE_FEE_CENTS ?? 200),
}));
export interface PriceQuote {
days: number; dailyPriceCents: number; subtotalCents: number;
serviceFeeCents: number; totalPriceCents: number; depositCents: number; currency: string;
}
@Injectable()
export class PricingService {
constructor(@Inject(pricingConfig.KEY) private readonly cfg: ConfigType<typeof pricingConfig>) {}
/** Server-side, authoritative price. Clients never submit prices. */
quote(listing: Listing, startDate: string, endDate: string): PriceQuote {
const days = daysBetween(startDate, endDate);
const subtotalCents = listing.dailyPriceCents * days;
const serviceFeeCents = Math.max(
this.cfg.minServiceFeeCents,
Math.round((subtotalCents * this.cfg.renterServiceFeeBps) / 10_000),
);
return {
days, dailyPriceCents: listing.dailyPriceCents, subtotalCents, serviceFeeCents,
totalPriceCents: subtotalCents + serviceFeeCents, depositCents: listing.depositCents, currency: listing.currency,
};
}
}
// src/bookings/dto/create-booking.dto.ts
import { IsInt, IsISO8601, IsOptional, IsString, IsUUID, Matches, MaxLength, Min } from 'class-validator';
const DATE = /^\d{4}-\d{2}-\d{2}$/;
export class CreateBookingDto {
@IsUUID('4') listing_id!: string;
@Matches(DATE) @IsISO8601({ strict: true }) start_date!: string;
@Matches(DATE) @IsISO8601({ strict: true }) end_date!: string;
@IsOptional() @IsString() @MaxLength(1000) message?: string;
@IsOptional() @IsInt() @Min(0) expected_total_price_cents?: number;
}
export class ReasonDto {
@IsString() @MaxLength(500) @Matches(/\S{3,}/, { message: 'reason must contain at least 3 characters' })
reason!: string;
}
// src/bookings/bookings.service.ts
import { Injectable, Logger } from '@nestjs/common';
import { DataSource, EntityManager } from 'typeorm';
import { Booking, BookingStatus } from './booking.entity';
import { Listing, ListingStatus } from '../listings/listing.entity';
import { AvailabilitySlot, SlotKind } from '../availability/availability-slot.entity';
import { Payment, PaymentKind, PaymentStatus } from '../payments/payment.entity';
import { PricingService } from './pricing.service';
import { PaymentsService } from '../payments/payments.service';
import { OutboxService } from '../common/outbox/outbox.service';
import { AuditService } from '../common/audit/audit.service';
import { CreateBookingDto } from './dto/create-booking.dto';
import {
BOOKING_TRANSITIONS, BookingAction, daysBetween, refundFraction, resolveActor, todayIn,
} from './booking-state-machine';
import { DomainError, Errors, FieldError } from '../common/errors/domain.error';
import type { AuthPrincipal } from '../auth/decorators';
import { BookingDto, toBookingDto } from './booking.mapper';
const PAYMENT_HOLD_MINUTES = 30;
const MAX_RENTAL_DAYS = 30;
const MAX_LEAD_DAYS = 365;
@Injectable()
export class BookingsService {
private readonly logger = new Logger(BookingsService.name);
constructor(
private readonly dataSource: DataSource,
private readonly pricing: PricingService,
private readonly payments: PaymentsService,
private readonly outbox: OutboxService,
private readonly audit: AuditService,
) {}
async create(principal: AuthPrincipal, dto: CreateBookingDto): Promise<BookingDto & { payment_client_secret: string }> {
// Read from the PRIMARY to avoid booking against stale replica data
const listing = await this.dataSource.manager.findOne(Listing, { where: { id: dto.listing_id } });
if (!listing || listing.status !== ListingStatus.Published) throw Errors.notFound('Listing');
if (listing.ownerId === principal.userId) {
throw new DomainError(422, 'cannot_book_own_listing', 'You cannot book your own listing');
}
this.assertDateRange(dto.start_date, dto.end_date, listing.timezone);
const quote = this.pricing.quote(listing, dto.start_date, dto.end_date);
if (dto.expected_total_price_cents !== undefined && dto.expected_total_price_cents !== quote.totalPriceCents) {
throw Errors.priceChanged(dto.expected_total_price_cents, quote.totalPriceCents);
}
// 1) Short DB transaction: booking + date hold + payment row. The exclusion constraint makes
// concurrent overlapping requests fail atomically (→ 409 dates_unavailable via the filter).
const { booking, payment } = await this.dataSource.transaction(async (em) => {
const booking = await em.save(em.create(Booking, {
listingId: listing.id, renterId: principal.userId, ownerId: listing.ownerId,
startDate: dto.start_date, endDate: dto.end_date, status: BookingStatus.Pending,
dailyPriceCents: quote.dailyPriceCents, totalPriceCents: quote.totalPriceCents,
serviceFeeCents: quote.serviceFeeCents, depositCents: quote.depositCents, currency: quote.currency,
cancellationPolicy: listing.cancellationPolicy, renterMessage: dto.message ?? null,
expiresAt: new Date(Date.now() + PAYMENT_HOLD_MINUTES * 60_000),
}));
await em.insert(AvailabilitySlot, {
listingId: listing.id, startDate: dto.start_date, endDate: dto.end_date,
kind: SlotKind.Booked, bookingId: booking.id,
});
const payment = await em.save(em.create(Payment, {
bookingId: booking.id, kind: PaymentKind.Rental, amountCents: quote.totalPriceCents,
currency: quote.currency, status: PaymentStatus.RequiresAction,
idempotencyKey: `booking:${booking.id}:rental:authorize`, // deterministic → safe Stripe retries
}));
booking.paymentId = payment.id;
await em.update(Booking, booking.id, { paymentId: payment.id });
await this.audit.record({ actorId: principal.userId, action: 'booking.requested', resource: `booking:${booking.id}` }, em);
return { booking, payment };
});
// 2) Network call OUTSIDE the transaction: never hold a pooled connection across a Stripe round-trip.
try {
const intent = await this.payments.createManualCaptureIntent(payment, {
customerUserId: principal.userId,
description: `GearLoop booking ${booking.id}`,
metadata: { booking_id: booking.id, listing_id: listing.id },
});
return { ...toBookingDto(booking, 'renter'), payment_client_secret: intent.clientSecret };
} catch (err) {
this.logger.error({ err, bookingId: booking.id }, 'PaymentIntent creation failed; releasing hold');
await this.releaseHold(booking.id, 'payment_setup_failed');
throw Errors.paymentProvider();
}
}
async transition(principal: AuthPrincipal, bookingId: string, action: BookingAction, reason?: string): Promise<BookingDto> {
const em = this.dataSource.manager;
const booking = await em.findOne(Booking, { where: { id: bookingId } });
const actor = booking && resolveActor(principal.userId, principal.permissions.includes('admin:all'), booking);
if (!booking || !actor) throw Errors.notFound('Booking'); // non-parties get 404
const rule = BOOKING_TRANSITIONS[action];
if (!rule.actors.includes(actor)) throw Errors.forbiddenAction(`Only ${rule.actors.join('/')} can ${action}`);
if (!rule.from.includes(booking.status)) throw Errors.invalidTransition(booking.status, action);
if (rule.requiresReason && !reason) {
throw Errors.validation([{ field: 'reason', message: 'reason is required', code: 'required' }]);
}
const payment = booking.paymentId ? await em.findOne(Payment, { where: { id: booking.paymentId } }) : null;
const listing = await em.findOneOrFail(Listing, { where: { id: booking.listingId }, select: { id: true, timezone: true } });
const today = todayIn(listing.timezone);
const guardError = rule.guard?.({ booking, paymentStatus: payment?.status, today });
if (guardError) throw guardError;
const refundCents = rule.to === BookingStatus.Cancelled ? this.computeRefund(booking, today, actor) : null;
const updated = await this.dataSource.transaction(async (tx) => {
// Compare-and-set: concurrent actions (owner confirms while renter cancels) → exactly one wins
const res = await tx.createQueryBuilder()
.update(Booking)
.set({
status: rule.to,
version: () => 'version + 1',
...(reason ? { cancellationReason: reason } : {}),
...(refundCents !== null ? { refundCents } : {}),
...(rule.to === BookingStatus.Completed ? { completedAt: () => 'now()' } : {}),
...(rule.to === BookingStatus.Confirmed || rule.to === BookingStatus.Cancelled ? { expiresAt: null } : {}),
})
.where('id = :id AND status = :from', { id: bookingId, from: booking.status })
.returning('*')
.execute();
if (!res.affected) throw Errors.concurrentModification();
if (rule.to === BookingStatus.Cancelled) await tx.delete(AvailabilitySlot, { bookingId });
// Side effects (capture / void / refund / deposit release / notifications) run via the outbox:
// committed atomically with the state change, executed by workers with Stripe idempotency keys.
await this.outbox.enqueue(tx, `booking.${action}`, { bookingId, actor, refundCents });
await this.audit.record({
actorId: principal.userId, action: `booking.${action}`, resource: `booking:${bookingId}`,
diff: { from: booking.status, to: rule.to, reason, refundCents },
}, tx);
return tx.create(Booking, res.raw[0]);
});
return toBookingDto(updated, actor);
}
/** Used by the expiry job, the payment-failure webhook and compensation paths. Idempotent. */
async releaseHold(bookingId: string, reason: string, em: EntityManager = this.dataSource.manager): Promise<void> {
await em.transaction(async (tx) => {
const res = await tx.update(Booking, { id: bookingId, status: BookingStatus.Pending },
{ status: BookingStatus.Cancelled, cancellationReason: reason, expiresAt: null });
if (res.affected) {
await tx.delete(AvailabilitySlot, { bookingId });
await this.outbox.enqueue(tx, 'booking.expired', { bookingId, reason });
}
});
}
private computeRefund(b: Booking, today: string, actor: 'renter' | 'owner' | 'admin'): number {
const fraction = refundFraction(b.cancellationPolicy, b, today, actor);
const subtotal = b.totalPriceCents - b.serviceFeeCents;
return Math.round(subtotal * fraction) + (fraction === 1 ? b.serviceFeeCents : 0);
}
private assertDateRange(start: string, end: string, timeZone: string): void {
const errors: FieldError[] = [];
const today = todayIn(timeZone);
const days = daysBetween(start, end);
if (start < today) errors.push({ field: 'start_date', message: 'start_date cannot be in the past', code: 'in_past' });
if (days < 1) errors.push({ field: 'end_date', message: 'end_date must be after start_date', code: 'invalid_range' });
if (days > MAX_RENTAL_DAYS) errors.push({ field: 'end_date', message: `Maximum rental is ${MAX_RENTAL_DAYS} days`, code: 'range_too_long' });
if (daysBetween(today, start) > MAX_LEAD_DAYS) errors.push({ field: 'start_date', message: 'Too far in advance', code: 'too_far_ahead' });
if (errors.length) throw Errors.validation(errors);
}
}
// src/bookings/bookings.controller.ts
import { Body, Controller, Get, HttpCode, Param, ParseUUIDPipe, Post, Query, Res } from '@nestjs/common';
import type { Response } from 'express';
import { Throttle } from '@nestjs/throttler';
import { BookingsService } from './bookings.service';
import { BookingsQueryService } from './bookings-query.service';
import { CreateBookingDto, ReasonDto } from './dto/create-booking.dto';
import { DisputeDto } from './dto/dispute.dto';
import { ListBookingsQuery } from './dto/list-bookings.query';
import { CurrentUser, RequireScopes, type AuthPrincipal } from '../auth/decorators';
import { Idempotent } from '../common/idempotency/idempotent.decorator';
const BookingId = () => new ParseUUIDPipe({ version: '4' });
@Controller({ path: 'bookings', version: '1' })
export class BookingsController {
constructor(private readonly bookings: BookingsService, private readonly queries: BookingsQueryService) {}
@Post()
@RequireScopes('bookings:write')
@Idempotent()
@Throttle({ default: { limit: 10, ttl: 60_000 } }) // stop date-hold abuse / card testing
async create(@CurrentUser() user: AuthPrincipal, @Body() dto: CreateBookingDto, @Res({ passthrough: true }) res: Response) {
const booking = await this.bookings.create(user, dto);
res.setHeader('Location', `/api/v1/bookings/${booking.id}`);
return booking;
}
@Get()
list(@CurrentUser() user: AuthPrincipal, @Query() q: ListBookingsQuery) {
return this.queries.list(user, q); // role=owner requires bookings:manage (checked in service)
}
@Get(':id')
get(@CurrentUser() user: AuthPrincipal, @Param('id', BookingId()) id: string) {
return this.queries.getForParty(user, id);
}
@Post(':id/confirm') @HttpCode(200) @RequireScopes('bookings:manage')
confirm(@CurrentUser() u: AuthPrincipal, @Param('id', BookingId()) id: string) {
return this.bookings.transition(u, id, 'confirm');
}
@Post(':id/decline') @HttpCode(200) @RequireScopes('bookings:manage')
decline(@CurrentUser() u: AuthPrincipal, @Param('id', BookingId()) id: string, @Body() b: ReasonDto) {
return this.bookings.transition(u, id, 'decline', b.reason);
}
@Post(':id/cancel') @HttpCode(200) @RequireScopes('bookings:write') @Idempotent()
cancel(@CurrentUser() u: AuthPrincipal, @Param('id', BookingId()) id: string, @Body() b: ReasonDto) {
return this.bookings.transition(u, id, 'cancel', b.reason);
}
@Post(':id/start') @HttpCode(200) @RequireScopes('bookings:manage')
start(@CurrentUser() u: AuthPrincipal, @Param('id', BookingId()) id: string) {
return this.bookings.transition(u, id, 'start');
}
@Post(':id/complete') @HttpCode(200) @RequireScopes('bookings:manage')
complete(@CurrentUser() u: AuthPrincipal, @Param('id', BookingId()) id: string) {
return this.bookings.transition(u, id, 'complete');
}
@Post(':id/dispute') @HttpCode(200) @RequireScopes('bookings:write') @Idempotent()
dispute(@CurrentUser() u: AuthPrincipal, @Param('id', BookingId()) id: string, @Body() b: DisputeDto) {
return this.bookings.transition(u, id, 'dispute', `${b.category}: ${b.description}`);
}
}
4.10 Payments: Stripe intent creation and webhook
// src/payments/payments.service.ts (excerpt)
import { Inject, Injectable } from '@nestjs/common';
import Stripe from 'stripe';
import { STRIPE_CLIENT } from './stripe.provider';
import { Payment } from './payment.entity';
import { DataSource } from 'typeorm';
import { UsersService } from '../users/users.service';
@Injectable()
export class PaymentsService {
constructor(
@Inject(STRIPE_CLIENT) private readonly stripe: Stripe,
private readonly dataSource: DataSource,
private readonly users: UsersService,
) {}
async createManualCaptureIntent(
payment: Payment,
opts: { customerUserId: string; description: string; metadata: Record<string, string> },
): Promise<{ clientSecret: string }> {
const customer = await this.users.ensureStripeCustomer(opts.customerUserId);
const intent = await this.stripe.paymentIntents.create(
{
amount: payment.amountCents,
currency: payment.currency.toLowerCase(),
customer,
capture_method: 'manual', // authorize now, capture on owner confirm
setup_future_usage: 'off_session', // reuse card for the deposit hold before pickup
automatic_payment_methods: { enabled: true },
description: opts.description,
metadata: { ...opts.metadata, payment_id: payment.id },
transfer_group: opts.metadata.booking_id, // links the later Connect transfer (payout)
},
{ idempotencyKey: payment.idempotencyKey }, // deterministic: retries never double-charge
);
await this.dataSource.manager.update(Payment, payment.id, { stripePaymentIntentId: intent.id });
return { clientSecret: intent.client_secret! };
}
}
// src/payments/stripe-webhook.controller.ts
import { Controller, Headers, HttpCode, Inject, Post, RawBodyRequest, Req } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SkipThrottle } from '@nestjs/throttler';
import type { Request } from 'express';
import Stripe from 'stripe';
import { Public } from '../auth/decorators';
import { DomainError } from '../common/errors/domain.error';
import { STRIPE_CLIENT } from './stripe.provider';
import { StripeEventsService } from './stripe-events.service';
@Controller({ path: 'webhooks', version: '1' })
export class StripeWebhookController {
private readonly secret: string;
constructor(
@Inject(STRIPE_CLIENT) private readonly stripe: Stripe,
private readonly events: StripeEventsService,
config: ConfigService,
) {
this.secret = config.getOrThrow('STRIPE_WEBHOOK_SECRET');
}
@Post('stripe')
@Public()
@SkipThrottle() // protected by signature verification + WAF IP allowlist for Stripe ranges
@HttpCode(200)
async handle(@Req() req: RawBodyRequest<Request>, @Headers('stripe-signature') signature?: string) {
if (!req.rawBody || !signature) throw new DomainError(400, 'invalid_signature', 'Missing signature');
let event: Stripe.Event;
try {
event = this.stripe.webhooks.constructEvent(req.rawBody, signature, this.secret); // also rejects stale timestamps
} catch {
throw new DomainError(400, 'invalid_signature', 'Invalid Stripe signature');
}
// INSERT INTO stripe_events (id, type, payload) ON CONFLICT (id) DO NOTHING → enqueue to BullMQ.
// Respond fast. Processing is async, idempotent, and tolerant of out-of-order delivery.
await this.events.persistAndEnqueue(event);
return { received: true };
}
}
// src/payments/stripe-events.processor.ts (excerpt: BullMQ worker)
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Job } from 'bullmq';
import { DataSource } from 'typeorm';
import Stripe from 'stripe';
import { Payment, PaymentStatus } from './payment.entity';
import { Booking, BookingStatus } from '../bookings/booking.entity';
import { BookingsService } from '../bookings/bookings.service';
const OWNER_RESPONSE_WINDOW_MS = 24 * 3600 * 1000;
@Processor('stripe-events', { concurrency: 10 })
export class StripeEventsProcessor extends WorkerHost {
constructor(private readonly dataSource: DataSource, private readonly bookings: BookingsService) { super(); }
async process(job: Job<Stripe.Event>): Promise<void> {
const event = job.data;
switch (event.type) {
case 'payment_intent.amount_capturable_updated': { // authorized (incl. after 3DS)
const pi = event.data.object as Stripe.PaymentIntent;
await this.dataSource.transaction(async (tx) => {
const res = await tx.update(Payment,
{ stripePaymentIntentId: pi.id, status: PaymentStatus.RequiresAction },
{ status: PaymentStatus.Authorized });
if (res.affected) {
// Payment secured → give owner 24h to respond
await tx.update(Booking, { id: pi.metadata.booking_id, status: BookingStatus.Pending },
{ expiresAt: new Date(Date.now() + OWNER_RESPONSE_WINDOW_MS) });
}
});
break;
}
case 'payment_intent.succeeded':
await this.dataSource.manager.update(Payment,
{ stripePaymentIntentId: (event.data.object as Stripe.PaymentIntent).id }, { status: PaymentStatus.Captured });
break;
case 'payment_intent.payment_failed': {
const pi = event.data.object as Stripe.PaymentIntent;
await this.dataSource.manager.update(Payment, { stripePaymentIntentId: pi.id }, { status: PaymentStatus.Failed });
await this.bookings.releaseHold(pi.metadata.booking_id, 'payment_failed');
break;
}
// charge.refunded → refunded/partially_refunded; account.updated → owner payouts_enabled;
// transfer.created / transfer.reversed → payout status.
default:
break;
}
await this.dataSource.query('UPDATE stripe_events SET processed_at = now() WHERE id = $1', [event.id]);
}
}
4.11 Migration: constraints and indexes that carry the design
-- migrations/1732400000000-core-constraints.sql (run via TypeORM migration `queryRunner.query`)
CREATE EXTENSION IF NOT EXISTS postgis;
CREATE EXTENSION IF NOT EXISTS btree_gist; -- allows `listing_id WITH =` inside a GiST exclusion constraint
CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- ── Availability: no overlapping ranges per listing, ever ──────────────────────────
CREATE TYPE slot_kind AS ENUM ('blocked', 'booked');
CREATE TABLE availability_slots (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
listing_id uuid NOT NULL REFERENCES listings(id) ON DELETE CASCADE,
start_date date NOT NULL,
end_date date NOT NULL,
kind slot_kind NOT NULL,
booking_id uuid UNIQUE REFERENCES bookings(id) ON DELETE CASCADE,
note text,
period daterange GENERATED ALWAYS AS (daterange(start_date, end_date, '[)')) STORED,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT slot_valid_range CHECK (end_date > start_date),
CONSTRAINT slot_kind_matches CHECK ((kind = 'booked') = (booking_id IS NOT NULL)),
CONSTRAINT availability_no_overlap EXCLUDE USING gist (listing_id WITH =, period WITH &&)
);
-- ── Bookings ───────────────────────────────────────────────────────────────────────
ALTER TABLE bookings
ADD CONSTRAINT booking_valid_range CHECK (end_date > start_date),
ADD CONSTRAINT booking_not_self CHECK (renter_id <> owner_id),
ADD CONSTRAINT booking_money_nonneg CHECK (total_price_cents >= 0 AND deposit_cents >= 0 AND service_fee_cents >= 0);
CREATE INDEX idx_bookings_renter ON bookings (renter_id, created_at DESC, id DESC);
CREATE INDEX idx_bookings_owner_status ON bookings (owner_id, status, start_date);
CREATE INDEX idx_bookings_listing ON bookings (listing_id, start_date);
CREATE INDEX idx_bookings_pending_exp ON bookings (expires_at) WHERE status = 'pending';
CREATE INDEX idx_bookings_autocomplete ON bookings (end_date) WHERE status = 'active';
-- ── Listings: geo, full-text, filters ─────────────────────────────────────────────
ALTER TABLE listings ADD COLUMN search_vector tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(description, '')), 'B')
) STORED;
CREATE INDEX idx_listings_geog_pub ON listings USING gist (geog) WHERE status = 'published';
CREATE INDEX idx_listings_fts_pub ON listings USING gin (search_vector) WHERE status = 'published';
CREATE INDEX idx_listings_cat_price ON listings (category_id, daily_price_cents, id) WHERE status = 'published';
CREATE INDEX idx_listings_price ON listings (daily_price_cents, id) WHERE status = 'published';
CREATE INDEX idx_listings_created ON listings (created_at DESC, id DESC) WHERE status = 'published';
CREATE INDEX idx_listings_rating ON listings ((COALESCE(rating_avg, 0)) DESC, id DESC) WHERE status = 'published';
CREATE INDEX idx_listings_owner ON listings (owner_id, status);
-- Privacy: deterministic ~radius_m offset so repeated requests can't be averaged to the true point
CREATE OR REPLACE FUNCTION fuzz_point(g geography, radius_m int) RETURNS geography
LANGUAGE sql IMMUTABLE AS $$
SELECT ST_Project(g, radius_m * (0.5 + 0.5 * ((('x' || substr(md5(ST_AsText(g)), 1, 8))::bit(32)::int & 1023) / 1023.0)),
radians((('x' || substr(md5(ST_AsText(g)), 9, 8))::bit(32)::int & 1023) * 360.0 / 1023.0));
$$;
-- ── Categories: materialized slug path for subtree filtering ──────────────────────
CREATE INDEX idx_categories_path ON categories (path text_pattern_ops);
-- ── Payments / payouts ─────────────────────────────────────────────────────────────
CREATE UNIQUE INDEX uq_payments_intent ON payments (stripe_payment_intent_id) WHERE stripe_payment_intent_id IS NOT NULL;
CREATE UNIQUE INDEX uq_payments_idempotency ON payments (idempotency_key);
CREATE UNIQUE INDEX uq_payments_booking_kind ON payments (booking_id, kind);
CREATE INDEX idx_payments_unpaid ON payments (booking_id) WHERE status = 'captured' AND payout_id IS NULL;
CREATE INDEX idx_payouts_owner ON payouts (owner_id, created_at DESC, id DESC);
CREATE TABLE stripe_events (
id text PRIMARY KEY, type text NOT NULL, payload jsonb NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(), processed_at timestamptz
);
-- ── Reviews, messaging ─────────────────────────────────────────────────────────────
CREATE UNIQUE INDEX uq_reviews_booking_author ON reviews (booking_id, author_id);
CREATE INDEX idx_reviews_target ON reviews (target_type, target_id, published_at DESC, id DESC) WHERE published_at IS NOT NULL;
CREATE UNIQUE INDEX uq_conversation_pair ON conversations (listing_id, renter_id, owner_id);
CREATE INDEX idx_conversations_renter ON conversations (renter_id, last_message_at DESC, id DESC);
CREATE INDEX idx_conversations_owner ON conversations (owner_id, last_message_at DESC, id DESC);
CREATE INDEX idx_messages_conv ON messages (conversation_id, created_at DESC, id DESC);
-- ── Users ──────────────────────────────────────────────────────────────────────────
CREATE UNIQUE INDEX uq_users_auth0_sub ON users (auth0_sub);
CREATE UNIQUE INDEX uq_users_email ON users (lower(email));
-- ── Outbox & audit ─────────────────────────────────────────────────────────────────
CREATE TABLE outbox (
id bigserial PRIMARY KEY, topic text NOT NULL, payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(), dispatched_at timestamptz
);
CREATE INDEX idx_outbox_pending ON outbox (id) WHERE dispatched_at IS NULL;
CREATE TABLE audit_events (
id bigserial PRIMARY KEY,
occurred_at timestamptz NOT NULL DEFAULT now(),
actor_id uuid, actor_type text NOT NULL DEFAULT 'user', -- user | admin | system | stripe
action text NOT NULL, resource text NOT NULL,
diff jsonb, request_id text, ip inet, user_agent text
);
CREATE INDEX idx_audit_resource ON audit_events (resource, occurred_at DESC);
-- Append-only: the app role gets INSERT/SELECT only
REVOKE UPDATE, DELETE ON audit_events FROM gearloop_app;
5. Scalability Notes
Load profile
| Metric | Steady | Peak (summer/holiday) | Design target |
|---|---|---|---|
| Requests/s | 150 | 800 | 2,000 (2.5× headroom) |
| Read:write ratio | ~90:10 | ~93:7 (search-heavy) | |
| Bookings/s (writes) | < 1 | ~5–10 | Exclusion constraint handles contention |
| Search p95 | < 150 ms | < 250 ms | GiST + partial indexes + 30s cache |
This is modest for Postgres. The risks are connection exhaustion during bursts, hot-listing contention, and search query plans, not raw throughput.
Connection pooling
- Sizing math. At 800 req/s, roughly 2.5 queries per request and roughly 4 ms average query time, the API needs about
800 × 2.5 × 0.004 ≈ 8concurrently busy connections. Allow about 3× for variance, which gives ≈ 25–40 server connections on the primary. - App side. Run 6 pods at peak with
max: 15each, for about 90 client connections, through PgBouncer in transaction mode. PgBouncer usesdefault_pool_size = 40on the primary and about 30 per replica. Postgresmax_connectionsstays around 200. - Fail fast.
connectionTimeoutMillis: 2000andstatement_timeout: 5smean overload returns 503 quickly instead of piling up queued requests. - PgBouncer caveats. Transaction mode breaks session-level features. Avoid
SEToutside a transaction, session advisory locks andLISTEN. UseSET LOCALand transaction-scoped locks instead. - Read/write split. Replicas serve public search, listing detail, the calendar and review lists. The primary serves anything after a write, plus ownership checks for mutations and booking creation. Monitor replica lag. If lag exceeds 5s, route reads back to the primary.
Caching (Redis plus CDN)
| Data | Layer | TTL | Invalidation |
|---|---|---|---|
| Category tree | CDN + Redis + in-process LRU | 1h | Admin write bumps the version key |
| Search results | CDN (public, max-age=30, swr=60) + Redis (key: normalized query, coordinates snapped to about 1 km) |
30s | TTL only (staleness acceptable; booking re-validates) |
| Listing detail (public) | Redis, plus CDN for anonymous requests | 5 min | DEL on update/publish/pause |
| Availability calendar | Redis | 30s | DEL on block or booking change (outbox consumer) |
| JWT → local user mapping | Redis | 60s | DEL on suspend or role change |
| JWKS | In-process (jwks-rsa) | 10 min | Auto-refetch on unknown kid |
| Photos | CDN with on-the-fly resize (e.g. CloudFront + Lambda@Edge or imgproxy) | 1y, immutable | Content-hashed URLs |
- Never cache the booking decision. Availability caches are advisory. The exclusion constraint is the source of truth.
- Use stale-while-revalidate and request coalescing at the CDN to absorb holiday-weekend search spikes. 800 req/s of search may only produce about 100 req/s at the origin.
Indexing and query strategy
- Geo search uses
ST_DWithin(geog, point, r)on a partial GiST index (WHERE status = 'published'). The planner prunes on the index before evaluating the date-overlapNOT EXISTSsubquery, which is itself served by the exclusion constraint's GiST index on(listing_id, period). - Keyset pagination with composite
(sort_key, id)indexes means page 50 costs the same as page 1. - Ratings are denormalized (
rating_avg,rating_count) and updated when a review is published. List endpoints never aggregate on read. - Run
EXPLAIN (ANALYZE, BUFFERS)in CI against seeded data (500k listings) for the five most frequent search shapes. Fail the build on sequential scans. - Growth path. If geo plus full-text plus faceting outgrows Postgres (multi-million listings, typo-tolerant search, or facet counts), move search to OpenSearch or Typesense, fed by the outbox (CDC). Keep Postgres for availability checks.
Throughput and resilience
- Autoscaling. NestJS pods (2 vCPU / 1 GiB) handle about 300–500 req/s each for this workload. Run a minimum of 3 replicas across availability zones and scale to about 8 on CPU above 60% or p95 above 300 ms. Pre-scale on a schedule before Friday afternoons in June through August.
- Background workers run in a separate deployment: outbox relay, BullMQ for Stripe events, notifications, the pending-hold expiry sweep (every minute), auto-complete (end_date + 48h), deposit authorization (start − 24h) and weekly payout batching. Workers are idempotent and retried with exponential backoff, with a dead-letter queue and alerting.
- Hot listings. The exclusion constraint serializes only same-listing overlapping inserts. A popular kayak on a holiday weekend fails fast with 409 instead of creating lock queues.
- Stripe calls use a circuit breaker with a 5s timeout, never run inside DB transactions, and always use deterministic idempotency keys.
- Postgres sizing. The primary needs about 8 vCPU / 32 GB (the 500k-listing working set fits in RAM). Add 1–2 replicas and enable PITR backups. Keep
autovacuumtuned forbookings,availability_slots,messagesandoutbox, and prune dispatched outbox rows daily. - Observability. Use OpenTelemetry traces (HTTP → TypeORM → Stripe) and RED metrics per route. Track business SLOs: booking-create success rate, 409 rate and webhook processing lag.
6. Security and Performance Checklist
Authentication and authorization
- Auth0 Authorization Code + PKCE for mobile and SPA. For web, prefer a BFF that holds tokens server-side behind
HttpOnly; Secure; SameSite=Strictcookies. - Access tokens: RS256, 15 min, validated for
iss,aud,expandnbf, algorithm pinned, JWKS cached with key rotation support. - Refresh tokens: rotation + reuse detection enabled in Auth0. Absolute lifetime 30 days, inactivity 7 days. Refresh tokens never reach the API.
- Auth0 RBAC with "Add Permissions in the Access Token" enabled.
ScopesGuardruns on every protected route, and routes default to authenticated:@Public()is an explicit opt-out. - Resource-level ownership checks in every service. Non-owners get 404 so IDs can't be enumerated.
- Suspension check on every request (cached 60s), which closes the 15-minute token-revocation gap. Admin suspension also revokes Auth0 refresh tokens through the Management API.
- Admin endpoints require
admin:alland Auth0 MFA, enforced with anamrclaim check in an Auth0 Action.
Input, output and data protection
-
ValidationPipewithwhitelist+forbidNonWhitelisted(mass-assignment protection). Every string has a max length, numbers have bounds, and the JSON body limit is 100 KB. - All SQL is parameterized. Sort and filter expressions come from server-side whitelists only.
- Prices and fees are computed server-side only.
expected_total_price_centsdetects drift but is never trusted as the price. - Photo URLs restricted to the GearLoop CDN host. Uploads use presigned S3 PUTs with content-type and size enforced in the policy, and are scanned (MIME sniffing plus malware scan) before publishing.
- PII minimization: public profiles show "First L." only. Exact location and phone are revealed only to the counterparty after confirmation. Email is never exposed to other users.
- Consistent RFC 7807 errors with a stable
codeandrequest_id. No stack traces or SQL messages leak in 5xx responses.
Abuse protection, idempotency and integrity
- Edge WAF and rate limits (per IP, bot management), plus app-level Redis throttling per user/IP. Stricter limits on
POST /bookings(10/min), messaging (30/min) and search (120/min). Responses includeRetry-AfterandX-RateLimit-*headers. -
Idempotency-Keyrequired on booking create, cancel, dispute and dispute resolution, with a 24h replay window, body fingerprinting and in-flight locking. - Database-level invariants: exclusion constraint (no double-booking), compare-and-set state transitions, unique constraints (reviews, conversations, payments), CHECK constraints on money and dates.
- Stripe: deterministic idempotency keys, manual capture, webhook signature verification over the raw body, event deduplication table, async processing tolerant of out-of-order delivery.
- Pending holds expire after 30 minutes unpaid or 24h unconfirmed, which stops attackers from blocking calendars.
Transport, CORS and headers
- TLS 1.2+ only (enforced at the edge), HSTS through Helmet,
trust proxyset correctly. - CORS: explicit origin allowlist per environment,
credentials: falsefor bearer-token clients,X-Request-IdandIdempotent-Replayedin the exposed headers. Never*.
Secrets and configuration
- Secrets (Stripe secret and webhook keys, Auth0 M2M secret, database credentials) live in AWS Secrets Manager or GCP Secret Manager and are injected at runtime. Never stored in the repo or image layers.
- Database access uses IAM or short-lived credentials where possible. Separate DB roles for app, migrations and read-only analytics. The app role cannot
UPDATEorDELETEaudit rows. - Stripe restricted API keys scoped to the required resources. Keys rotated quarterly, with dual-key overlap during rotation.
- Logs redact
Authorization, cookies, email and phone. Never log card data, which the API never touches anyway because Stripe Elements keeps it out of PCI scope (SAQ-A).
Audit logging
- Append-only
audit_eventsrecord booking transitions, refunds, payouts, dispute resolutions, listing publish/archive, role grants, suspensions and every admin action. Each record has actor, request_id, IP and a before/after diff. - Audit records are streamed to a SIEM or WORM storage. Retention is 7 years for financial events and 1 year for others, aligned with your legal requirements.
- Alerts on anomalies: spikes in 401/403, idempotency-key reuse, refunds above a threshold, and admin actions outside business hours.
Performance
- PgBouncer in transaction mode, small per-pod pools (15), 2s connection timeout, 5s statement timeout.
- Read replicas for public reads, with read-your-writes on the primary for mutations and booking flows.
- Partial GiST, GIN and B-tree indexes covering every search and sort shape, verified with
EXPLAINin CI. - Cursor pagination everywhere, with
limit ≤ 100and noCOUNT(*)on hot paths. - CDN plus Redis caching with stale-while-revalidate for search, categories and public listing detail. Availability is always re-checked transactionally.
- No external I/O inside DB transactions. Side effects go through the transactional outbox and BullMQ workers.
- Scheduled pre-scaling ahead of summer and holiday weekends. Load-test at 2,000 req/s with a realistic search/booking mix (k6) before June, including a "100 users book the same listing" contention test.
Suggested next steps
- Generate typed clients from the OpenAPI spec (
openapi-typescriptfor web, Swift and Kotlin for mobile). - Add
@nestjs/swaggerdecorators, or a contract test that diffs the generated spec against this one in CI. - Write integration tests (Testcontainers + PostGIS) for the exclusion constraint, the state machine races and the refund policy tables.
Related prompts
Algorithm Design Expert
Designs, analyzes, and optimizes algorithms with multiple approaches, Big-O complexity analysis, production code, and tests.
Python Development Specialist
Generates production-ready, fully typed Python code with tests, docstrings, and usage examples to your spec.
Professional Code Generator
Generates clean, well-documented, production-ready code from your requirements, following best practices in any language.
SQL Query Optimizer
Diagnoses a slow SQL query and returns an optimized rewrite, index plan, and execution-plan reasoning.