PromptBase
Upgrade
Close icon
General
Home
Marketplace
Create
Hire
Login
Chat
Sell
Explore

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
Claude

Backend Api Development Assistant

Add to Cart
Instant accessInstant access
Usage rightsCommercial use
Money-back guaranteeMoney‑back
By purchasing this prompt, you agree to our terms of service
CLAUDE-5-5-SONNET
Tested icon
Guide icon
4 examples icon
Free credits icon
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
Report
Browse Marketplace