Skip to main content

Backend Structure

Overview

The BookWish backend is a RESTful API server built with Node.js, Express, and TypeScript. It provides all backend services for the BookWish mobile app and web dashboard.

Technology Stack

Core Technologies

  • Runtime: Node.js 20+
  • Framework: Express 4.18
  • Language: TypeScript 5.3
  • Database: PostgreSQL (via Prisma ORM)
  • Cache/Queue: Redis (IORedis 5.3)
  • Job Queue: Bull 4.12

Key Dependencies

  • Prisma (5.8.0) - Database ORM and migrations
  • Helmet (7.1.0) - Security headers
  • Morgan (1.10.0) - HTTP request logging
  • JsonWebToken (9.0.2) - JWT authentication
  • Bcrypt (5.1.1) - Password hashing
  • Zod (3.22.4) - Schema validation
  • Axios (1.13.2) - HTTP client for external APIs

Third-Party Integrations

  • Stripe (20.0.0) - Payment processing and subscriptions
  • Square (43.2.1) - POS integration and inventory sync
  • AWS SES (@aws-sdk/client-ses 3.946) - Transactional email
  • Firebase Admin (13.6.0) - Push notifications
  • EasyPost (@easypost/api 8.4.0) - Shipping and fulfillment
  • Sharp (0.34.5) - Image processing
  • Multer (2.0.2) - File upload handling

Directory Structure

backend/
├── prisma/
│ ├── schema.prisma # Database schema
│ ├── migrations/ # Migration files
│ └── seed.ts # Database seeding

├── src/
│ ├── index.ts # Application entry point
│ ├── app.ts # Express app configuration
│ │
│ ├── config/ # Configuration files
│ │ ├── env.ts # Environment variables
│ │ ├── database.ts # Prisma client
│ │ └── redis.ts # Redis client
│ │
│ ├── routes/ # Route definitions
│ │ ├── index.ts # Main router (aggregates all routes)
│ │ ├── auth.routes.ts # Authentication routes
│ │ ├── user.routes.ts # User management
│ │ ├── book.routes.ts # Book catalog
│ │ ├── wishlist.routes.ts # Wishlist management
│ │ ├── store.routes.ts # Store management
│ │ ├── inventory.routes.ts # Store inventory
│ │ ├── order.routes.ts # Order management
│ │ ├── checkout.routes.ts # Checkout flow
│ │ ├── cart.routes.ts # Shopping cart
│ │ ├── pos.routes.ts # Point of sale
│ │ ├── line.routes.ts # Social lines (posts)
│ │ ├── review.routes.ts # Book reviews
│ │ ├── note.routes.ts # Personal notes
│ │ ├── follow.routes.ts # Social following
│ │ ├── feed.routes.ts # Activity feed
│ │ ├── search.routes.ts # Search endpoints
│ │ ├── club.routes.ts # Book clubs
│ │ ├── challenge.routes.ts # Reading challenges
│ │ ├── notification.routes.ts # Notifications
│ │ ├── webhook.routes.ts # Webhooks (Stripe, Square)
│ │ └── ... # Additional routes
│ │
│ ├── controllers/ # Request handlers
│ │ ├── auth.controller.ts
│ │ ├── book.controller.ts
│ │ ├── wishlist.controller.ts
│ │ └── ...
│ │
│ ├── services/ # Business logic layer
│ │ ├── auth.service.ts
│ │ ├── book.service.ts
│ │ ├── inventory.service.ts
│ │ ├── order.service.ts
│ │ ├── email.service.ts
│ │ ├── push.service.ts
│ │ └── ...
│ │
│ ├── middleware/ # Express middleware
│ │ ├── auth.middleware.ts # JWT authentication
│ │ ├── tier.middleware.ts # User tier gating
│ │ ├── store-owner.middleware.ts # Store ownership
│ │ ├── store-staff.middleware.ts # Store staff access
│ │ ├── admin.middleware.ts # Admin access
│ │ ├── cors.middleware.ts # CORS configuration
│ │ ├── logging.middleware.ts # Request logging
│ │ ├── error.middleware.ts # Error handling
│ │ └── rate-limit.middleware.ts # Rate limiting
│ │
│ ├── jobs/ # Background jobs
│ │ ├── queue.ts # Bull queue factory
│ │ ├── notification.job.ts # Push/email notifications
│ │ ├── square-sync.job.ts # Square inventory sync
│ │ ├── reservation-cleanup.job.ts # Inventory cleanup
│ │ └── order-digest.job.ts # Daily order digests
│ │
│ ├── integrations/ # Third-party API clients
│ │ ├── stripe.ts # Stripe payments
│ │ ├── square.ts # Square POS
│ │ ├── firebase.ts # Firebase push
│ │ ├── ses.ts # AWS SES email
│ │ ├── easypost.ts # Shipping
│ │ ├── google-books.ts # Book metadata
│ │ ├── isbndb.ts # ISBN lookup
│ │ ├── booksrun.ts # Wholesale pricing
│ │ └── ingram.ts # Ingram wholesale
│ │
│ ├── utils/ # Utility functions
│ │ ├── jwt.ts # JWT utilities
│ │ ├── password.ts # Password hashing
│ │ ├── encryption.ts # Data encryption
│ │ └── ...
│ │
│ ├── lib/ # Shared libraries
│ │ └── logger.ts # Logging utility
│ │
│ └── types/ # TypeScript type definitions
│ └── express.d.ts # Express extensions

├── package.json # Dependencies
├── tsconfig.json # TypeScript config
└── .env # Environment variables

Application Layers

1. Entry Point (index.ts)

  • Initializes database connection (Prisma)
  • Initializes Redis connection
  • Initializes Firebase Admin SDK
  • Initializes AWS SES
  • Schedules background jobs (Square sync, reservation cleanup, order digests)
  • Starts Express server
  • Handles graceful shutdown

2. Application (app.ts)

  • Configures Express middleware stack:
    • Helmet (security headers)
    • CORS
    • Request logging
    • Raw body parser for Stripe webhooks
    • JSON body parser
    • Routes
    • Error handler

3. Routes Layer

Routes define HTTP endpoints and apply appropriate middleware (auth, tier gates, ownership checks).

4. Controllers Layer

Controllers handle HTTP request/response logic:

  • Request validation
  • Calling service layer
  • Response formatting
  • Error handling

5. Services Layer

Services contain business logic:

  • Database operations
  • Business rules
  • Third-party API calls
  • Transaction management

6. Middleware Layer

Middleware provides cross-cutting concerns:

  • Authentication
  • Authorization (tier, store access)
  • Request logging
  • Error handling
  • Rate limiting

7. Jobs Layer

Background jobs handle asynchronous work:

  • Push notifications
  • Email sending
  • Inventory synchronization
  • Order digest emails
  • Cleanup tasks

8. Integrations Layer

Integration modules handle third-party APIs:

  • Payment processing (Stripe)
  • POS systems (Square)
  • Shipping (EasyPost)
  • Email (AWS SES)
  • Push notifications (Firebase)
  • Book metadata (Google Books, ISBNdb)

Environment Variables

Key environment variables (see .env):

# Database
DATABASE_URL=postgresql://...

# Redis
REDIS_URL=redis://...

# JWT
JWT_SECRET=...
JWT_ACCESS_EXPIRES_IN=15m
JWT_REFRESH_EXPIRES_IN=7d

# Stripe
STRIPE_SECRET_KEY=...
STRIPE_WEBHOOK_SECRET=...
STRIPE_PRODUCT_BOOKSTORE=...
STRIPE_PRICE_PREMIUM_MONTHLY=...

# Square
SQUARE_APP_ID=...
SQUARE_APP_SECRET=...
SQUARE_ENVIRONMENT=sandbox|production

# Firebase
FIREBASE_PROJECT_ID=...
FIREBASE_SERVICE_ACCOUNT=...

# AWS SES
AWS_REGION=us-east-1
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...

NPM Scripts

# Development
npm run dev # Start dev server with hot reload

# Build
npm run build # Compile TypeScript to dist/

# Production
npm start # Run compiled code

# Testing
npm test # Run Jest tests
npm run lint # Type check with tsc

# Database
npm run prisma:migrate # Create and apply migration
npm run prisma:generate # Generate Prisma client
npm run prisma:seed # Seed database

Deployment

The backend is designed to run on:

  • Compute: Cloud Run, ECS, or similar containerized environment
  • Database: Managed PostgreSQL (Cloud SQL, RDS, etc.)
  • Cache/Queue: Managed Redis (ElastiCache, Cloud Memorystore, etc.)

Startup Process

  1. Run database migrations (prisma migrate deploy)
  2. Start Express server
  3. Connect to PostgreSQL
  4. Connect to Redis
  5. Initialize Firebase Admin SDK
  6. Initialize AWS SES
  7. Schedule recurring jobs (Square sync, reservation cleanup, digests)
  8. Listen for HTTP requests

Graceful Shutdown

The server handles SIGTERM/SIGINT signals:

  1. Stop accepting new requests
  2. Close database connection
  3. Close Redis connection
  4. Exit with status code 0