Prompt Details
Model
(claude-5-5-sonnet)
Token size
3,720
Example input
[BACKEND_APPLICATION_REQUIREMENTS]: Build an e-commerce backend where customers can register, browse products, place orders, and view their orders. Admins can manage products and orders.
[TECHNOLOGY_STACK_AND_FRAMEWORK]: Node.js + TypeScript + Express + PostgreSQL + Prisma.
[DATA_ENTITIES_AND_BUSINESS_RULES]: Users, Products, Orders, Order Items. A customer can place orders. Product stock must decrease after a successful order.
[AUTHENTICATION_ROLES_AND_PERMISSIONS]: Customer and Admin roles. Customers manage their own orders. Admins manage products and all orders.
[SECURITY_VALIDATION_TESTING_AND_DEPLOYMENT_REQUIREMENTS]: JWT authentication, password hashing, input validation, rate limiting for login, automated tests, environment variables, and production deployment guidance.
Example output
## π PHASE 1 β Backend Requirement Reconstruction
### Explicit Requirements
- π€ Customer registration and login
- ποΈ Product browsing
- π Order creation
- π¦ Order history
- π¨βπΌ Admin product management
- π¨βπΌ Admin order management
- π JWT authentication
- ποΈ PostgreSQL database
- π Stock reduction after successful order
- π§ͺ Automated testing
### Derived Requirements
- Each order needs an owner.
- Each order contains one or more order items.
- Products need a stock quantity.
- Order creation should be transactional because order creation and stock reduction must remain consistent.
- Customer access to orders must be restricted to their own orders.
- Admins require elevated authorization.
### Assumptions
- Product prices are stored as monetary values using a database-safe numeric representation.
- An order records the product price at purchase time so historical orders do not change when the product price changes.
- No payment processing is included because no payment provider was supplied.
### Unresolved Questions
- Whether cancelled orders should restore stock.
- Whether products can be soft-deleted.
- Whether customers can cancel orders.
- Whether guest checkout is required.
---
# ποΈ PHASE 2 β Backend Architecture Design
Recommended architecture:
```text
Client
β
Express Routes
β
Authentication Middleware
β
Authorization Middleware
β
Request Validation
β
Controller
β
Service Layer
β
Prisma Data Access
β
PostgreSQL
```
### Layer Responsibilities
- π **Routes:** Define API endpoints.
- π **Authentication:** Verify JWT.
- π‘οΈ **Authorization:** Check customer/admin permissions.
- β
**Validation:** Validate request data.
- π― **Controllers:** Handle HTTP requests and responses.
- π§ **Services:** Implement business rules.
- ποΈ **Prisma:** Database access.
- π **PostgreSQL:** Persistent storage.
A microservice architecture is unnecessary for this requirement.
---
# ποΈ PHASE 3 β Database Schema Engineering
## π€ User
| Field | Type | Rule |
|---|---|---|
| id | UUID | Primary key |
| email | String | Unique, required |
| passwordHash | String | Required |
| role | Enum | CUSTOMER/ADMIN |
| createdAt | DateTime | Required |
| updatedAt | DateTime | Required |
Relationship:
```text
User 1 ββββββββ N Order
```
## ποΈ Product
| Field | Type | Rule |
|---|---|---|
| id | UUID | Primary key |
| name | String | Required |
| description | String | Required |
| price | Decimal | Required |
| stock | Integer | >= 0 |
| createdAt | DateTime | Required |
| updatedAt | DateTime | Required |
## π¦ Order
| Field | Type | Rule |
|---|---|---|
| id | UUID | Primary key |
| userId | UUID | Foreign key |
| status | Enum | Required |
| totalAmount | Decimal | Required |
| createdAt | DateTime | Required |
| updatedAt | DateTime | Required |
## π§Ύ OrderItem
| Field | Type | Rule |
|---|---|---|
| id | UUID | Primary key |
| orderId | UUID | Foreign key |
| productId | UUID | Foreign key |
| quantity | Integer | > 0 |
| unitPrice | Decimal | Required |
Relationship:
```text
Order 1 ββββββββ N OrderItem
Product 1 ββββββ N OrderItem
```
---
# π PHASE 4 β Data Integrity & Migration Design
### Order Creation Transaction
```text
BEGIN TRANSACTION
β
Validate products
β
Check stock
β
Create Order
β
Create Order Items
β
Decrease Product Stock
β
COMMIT
```
If any critical operation fails:
```text
ROLLBACK
```
### Integrity Rules
- π User email must be unique.
- π Order must reference an existing user.
- π OrderItem must reference an existing order.
- π OrderItem must reference an existing product.
- π Product stock cannot become negative.
- π Quantity must be greater than zero.
- π Order and stock changes should occur within one transaction.
---
# π PHASE 5 β API Contract Architecture
REST is appropriate because the supplied workflow is resource-oriented.
### Authentication
```text
POST /api/auth/register
POST /api/auth/login
```
### Products
```text
GET /api/products
GET /api/products/:id
POST /api/products
PATCH /api/products/:id
DELETE /api/products/:id
```
### Orders
```text
POST /api/orders
GET /api/orders
GET /api/orders/:id
```
### Admin Orders
```text
GET /api/admin/orders
PATCH /api/admin/orders/:id/status
```
### Authorization
```text
GET /api/products
β Public
POST /api/products
β Admin
PATCH /api/products/:id
β Admin
DELETE /api/products/:id
β Admin
POST /api/orders
β Customer
GET /api/orders
β Authenticated Customer
GET /api/admin/orders
β Admin
```
---
# π PHASE 6 β Authentication Implementation
Authentication flow:
```text
Register
β
Validate email/password
β
Hash password
β
Store password hash
```
Login:
```text
Email + Password
β
Find User
β
Compare Password
β
Generate JWT
β
Return Token
```
Important security requirement:
β Never store:
```text
password = "mypassword123"
```
Instead store a strong password hash.
JWT payload should contain only necessary identity information, such as:
```text
userId
role
```
The exact JWT expiration and refresh-token strategy remain deployment decisions because they were not specified in the input.
---
# π‘οΈ PHASE 7 β Authorization & Access Control
| Role | Resource | Action | Result |
|---|---|---|---|
| Customer | Products | Read | Allowed |
| Customer | Own Orders | Read | Allowed |
| Customer | Own Orders | Create | Allowed |
| Customer | Other Customer Orders | Read | Denied |
| Customer | Products | Create | Denied |
| Customer | Products | Delete | Denied |
| Admin | Products | Create | Allowed |
| Admin | Products | Update | Allowed |
| Admin | Products | Delete | Allowed |
| Admin | All Orders | Read | Allowed |
| Admin | Orders | Update Status | Allowed |
### Critical Rule
Authentication answers:
```text
"Who are you?"
```
Authorization answers:
```text
"What are you allowed to do?"
```
Both must be enforced server-side.
---
# β
PHASE 8 β Input Validation & Data Sanitization
### Registration
Validate:
- Email format
- Email length
- Password minimum requirements
- Required fields
### Product
Validate:
- Name is not empty
- Price is valid
- Price is not negative
- Stock is an integer
- Stock is not negative
### Order
Validate:
- Product ID exists
- Quantity is an integer
- Quantity > 0
- Requested quantity <= available stock
### Path Parameters
Example:
```text
/api/products/:id
```
The ID must be validated before database operations.
Frontend validation is not trusted.
---
# π§ PHASE 9 β Business Logic & Service Layer
## Create Order
```text
Order Request
β
Validate Input
β
Authenticate User
β
Check Authorization
β
Load Products
β
Check Stock
β
Calculate Total
β
Create Order
β
Create Order Items
β
Decrease Stock
β
Commit Transaction
β
Return Order
```
### Important Business Rule
If the requested quantity is greater than available stock:
```text
Order creation = FAILED
Stock = unchanged
```
If order creation succeeds:
```text
Order = created
Order Items = created
Stock = decreased
```
These operations should not partially succeed.
---
# π§― PHASE 10 β Error Handling & Failure Architecture
Use a consistent error format.
Example:
```json
{
"error": {
"code": "INSUFFICIENT_STOCK",
"message": "The requested quantity is not available.",
"requestId": "..."
}
}
```
### Error Categories
- π‘ `400` β Invalid request
- π `401` β Authentication required/invalid
- π« `403` β Permission denied
- π `404` β Resource not found
- β οΈ `409` β Conflict
- π₯ `500` β Unexpected server error
Never return:
```text
Database password
JWT secret
Stack trace
Internal SQL details
```
to the client.
---
# π» PHASE 11 β Step-by-Step Implementation
### Step 1 β Project Structure
```text
src/
βββ config/
βββ controllers/
βββ middleware/
βββ routes/
βββ services/
βββ validators/
βββ utils/
βββ tests/
βββ app.ts
```
### Step 2 β Configuration
Environment variables:
```text
DATABASE_URL
JWT_SECRET
PORT
NODE_ENV
```
### Step 3 β Database
Configure Prisma with PostgreSQL.
### Step 4 β Models
Create:
```text
User
Product
Order
OrderItem
```
### Step 5 β Authentication
Implement:
```text
register()
login()
verifyToken()
```
### Step 6 β Authorization
Implement middleware such as:
```text
requireAuth()
requireRole("ADMIN")
```
### Step 7 β Services
Create:
```text
UserService
ProductService
OrderService
```
### Step 8 β Routes
Connect controllers to REST endpoints.
### Step 9 β Error Handling
Create centralized error middleware.
### Step 10 β Tests
Run unit and integration tests.
---
# π§ͺ PHASE 12 β Backend Testing Architecture
### Unit Tests
Test:
- Password validation
- Product validation
- Order total calculation
- Stock validation
- Authorization logic
### Integration Tests
Test:
```text
Register
β Login
β Receive JWT
β Create Order
β Verify Stock Reduction
```
### Authorization Tests
Test that:
- Customer cannot create products.
- Customer cannot access another customer's order.
- Customer cannot access admin endpoints.
- Admin can manage products.
- Admin can view all orders.
### Critical Regression Test
```text
Product Stock = 5
Customer requests quantity = 6
Expected:
Order NOT created
Stock remains 5
```
The assistant must report actual test execution only if tests are actually run. It must not fabricate a successful result.
---
# β‘ PHASE 13 β API Performance & Reliability
### Database
Consider:
- Index on `User.email`
- Index on `Order.userId`
- Indexes on frequently queried product/order fields
### Pagination
Product listing should support pagination rather than returning an unlimited number of records.
Example:
```text
GET /api/products?page=1&limit=20
```
### Reliability
For database operations:
```text
Validate
β Transaction
β Commit
```
For external services, retry behavior would only be designed if an external dependency is actually introduced.
---
# π PHASE 14 β Security Checklist
| Security Area | Check | Risk | Required Action |
|---|---|---|---|
| Authentication | Password hashing | High | Required |
| Authentication | Login rate limiting | High | Required |
| Authorization | Role enforcement | High | Required |
| Authorization | Order ownership | Critical | Required |
| Input | Request validation | High | Required |
| Database | Parameterized ORM queries | High | Required |
| API | Rate limiting | Medium | Recommended |
| Secrets | Environment variables | High | Required |
| Errors | No stack traces | Medium | Required |
| Logs | No sensitive credentials | High | Required |
| Dependencies | Dependency auditing | Medium | Required |
| CORS | Explicit production policy | Medium | Required |
### π¨ Important Finding
The most important access-control test is preventing:
```text
Customer A
β
GET /api/orders/customer-B-order
```
The backend must verify resource ownership before returning the order.
---
# π PHASE 15 β API Documentation & Production Readiness
## Example Endpoint
### Create Order
```text
POST /api/orders
```
Authentication:
```text
Bearer JWT
```
Request:
```json
{
"items": [
{
"productId": "product-id",
"quantity": 2
}
]
}
```
Processing:
```text
Validate
β Authenticate
β Authorize
β Check Product
β Check Stock
β Calculate Total
β Create Order
β Decrease Stock
β Commit
```
### Production Checklist
- π Environment secrets configured
- ποΈ Database migrations controlled
- π Logging configured
- β€οΈ Health endpoint configured
- πΎ Database backups configured
- π Rollback strategy defined
- π¨ Error monitoring configured
- π§ͺ CI/CD tests configured
- π‘οΈ Rate limiting enabled
- π Production CORS policy configured
---
# π PHASE 16 β FINAL BACKEND BLUEPRINT
## 1. Architecture Summary
```text
REST API
β
Express
β
Middleware
β
Controllers
β
Services
β
Prisma
β
PostgreSQL
```
## 2. Core Data Model
```text
User
β
βββ< Order
β
βββ< OrderItem >ββ Product
```
## 3. API Strategy
**REST API** is appropriate because the requirements describe conventional resources and CRUD-style workflows.
## 4. Authentication
```text
Register
β Password Hash
β Database
Login
β Password Verification
β JWT
Request
β JWT Verification
β User Identity
```
## 5. Authorization
```text
Customer
β Own orders
Admin
β Products + all orders
```
## 6. Validation
All untrusted input must be validated server-side.
## 7. Business Logic
Order creation must preserve consistency between:
```text
Order
+
Order Items
+
Product Stock
```
## 8. Testing
The test suite must cover:
```text
Database
+
Validation
+
Authentication
+
Authorization
+
Services
+
REST APIs
+
Error Handling
+
Security
+
Regression
```
## 9. Security
Primary security priorities:
```text
JWT Security
+
Password Hashing
+
Object-Level Authorization
+
Input Validation
+
Rate Limiting
+
Secret Protection
+
Safe Error Handling
```
## 10. Deployment
Production deployment must include:
```text
Environment Configuration
β Database Migration
β Application Deployment
β Health Monitoring
β Logging
β Backups
β Rollback Strategy
```
### π― Final Test Verdict
**The prompt successfully handles the complete backend engineering lifecycle for this sample requirement:** requirements reconstruction β architecture β database β integrity β APIs β authentication β authorization β validation β business logic β errors β implementation β testing β performance β security β documentation β deployment.
It also follows the source prompt's key requirement that the assistant **must not invent unsupported business requirements or fabricate test/performance results.** Pasted text
By purchasing this prompt, you agree to our terms of service
CLAUDE-5-5-SONNET
Backend & API Development Assistant takes a backend requirement and systematically turns it into a database schema, REST/GraphQL API design, authentication system, validation layer, implementation code, testing plan, and security checklist.
ποΈ Design database schemas and relationships
π Build REST or GraphQL APIs step by step
π Implement authentication
Give the AI your backend requirements and build the server-side system step by step with security and validation built into the workflow.
...more
Added 6 days ago
