From 4b18067c03e57252db985cacef7e65b70ed0b283 Mon Sep 17 00:00:00 2001 From: Jackson Chen <541898146chen@gmail.com> Date: Sun, 17 Nov 2024 01:56:07 -0600 Subject: [PATCH] feat: Add BackendRequirementHandler for generating Backend Requirements Document This commit introduces the `BackendRequirementHandler` class, which implements the `BuildHandler` interface. The `run` method in this class generates the Backend Requirements Document based on the provided context data. The Backend Requirements Document includes the system overview, API endpoints, and implementation details. It provides guidelines for designing a clear system architecture, defining necessary API endpoints, and following RESTful or GraphQL conventions. The document also covers implementation details for request handlers/controllers, business logic layer/services, data access layer, and middleware components. This feature enhances the project builder functionality by providing the ability to generate a comprehensive Backend Requirements Document, ensuring a clear understanding of the backend system architecture and API endpoints. Co-authored-by: Jackson Chen <541898146chen@gmail.com> --- .../backend-requirements-document/index.ts | 74 ++++++++ .../backend-requirements-document/prompt.ts | 165 ++++++++++++++++++ 2 files changed, 239 insertions(+) create mode 100644 backend/src/build-system/node/backend-requirements-document/index.ts create mode 100644 backend/src/build-system/node/backend-requirements-document/prompt.ts diff --git a/backend/src/build-system/node/backend-requirements-document/index.ts b/backend/src/build-system/node/backend-requirements-document/index.ts new file mode 100644 index 00000000..e0bdc6e8 --- /dev/null +++ b/backend/src/build-system/node/backend-requirements-document/index.ts @@ -0,0 +1,74 @@ +import { BuildHandler, BuildResult } from 'src/build-system/types'; +import { BuilderContext } from 'src/build-system/context'; +import { + generateBackendImplementationPrompt, + generateBackendOverviewPrompt, +} from './prompt'; +import { Logger } from '@nestjs/common'; + +export class BackendRequirementHandler implements BuildHandler { + readonly id = 'op:BACKEND_REQ::STATE:GENERATE'; + + readonly logger: Logger = new Logger('BackendRequirementHandler'); + async run(context: BuilderContext, args: unknown): Promise { + this.logger.log('Generating Backend Requirements Document...'); + + // Validate and extract args + if (!args || typeof args !== 'object') { + throw new Error('Backend configuration is required'); + } + // TODO: init language, framework, packages later in context + const language = context.getData('language') || 'javascript'; + const framework = context.getData('framework') || 'express'; + const packages = context.getData('packages') || {}; + // TODO: adding graphql/restful later + + const { dbRequirements } = args as { + dbRequirements: string; + language: string; + framework: string; + packages: Record; + }; + + const overviewPrompt = generateBackendOverviewPrompt( + context.getData('projectName') || 'Default Project Name', + dbRequirements, + language, + framework, + packages, + ); + + const backendOverview = await context.model.chatSync( + { + content: overviewPrompt, + }, + 'gpt-4o-mini', + ); + + const implementationPrompt = generateBackendImplementationPrompt( + backendOverview, + language, + framework, + ); + + const implementationDetails = await context.model.chatSync( + { + content: implementationPrompt, + }, + 'gpt-4o-mini', + ); + + return { + success: true, + data: { + overview: backendOverview, + implementation: implementationDetails, + config: { + language, + framework, + packages, + }, + }, + }; + } +} diff --git a/backend/src/build-system/node/backend-requirements-document/prompt.ts b/backend/src/build-system/node/backend-requirements-document/prompt.ts new file mode 100644 index 00000000..e8b2f249 --- /dev/null +++ b/backend/src/build-system/node/backend-requirements-document/prompt.ts @@ -0,0 +1,165 @@ +// backend-overview-prompt.ts +export const generateBackendOverviewPrompt = ( + projectName: string, + dbRequirements: string, + language: string, + framework: string, + packages: Record, +): string => { + return `You are a Senior Backend Architect specializing in ${language} with ${framework}. Analyze the provided Database Requirements and generate the System Overview and API Endpoints specifications for ${projectName}. + +Database Requirements: +${dbRequirements} + +Technology Stack: +- Language: ${language} +- Framework: ${framework} +- Key Packages: +${Object.entries(packages) + .map(([pkg, version]) => ` - ${pkg}@${version}`) + .join('\n')} + +Generate a Backend Overview Document following these guidelines: + +### Instructions and Rules: +1. Design a clear system architecture based on the technology stack +2. Define all necessary API endpoints based on database requirements +3. Follow RESTful or GraphQL conventions as appropriate +4. Consider the relationships between different entities +5. Focus on clean and maintainable API design + +Your reply must start with: "\`\`\`BackendOverview" and end with "\`\`\`". + +Include these sections: + +#### 1. System Overview +- **Project Name**: ${projectName} +- **Technology Stack** + - Core technology choices + - Framework architecture + - Key dependencies and their purposes +- **Architecture Patterns** + - Framework-specific patterns + - Project structure + - Dependency management + - Configuration management + - Service organization + +#### 2. API Endpoints +For each endpoint: +\`\`\` +Route: /api/resource +Method: GET|POST|PUT/DELETE +Purpose: Functional description +Request: + Headers: { + "Authorization": "Bearer {token}" + // Other headers + } + Params: { + // URL parameters + } + Query: { + // Query parameters + } + Body: { + // Request body schema + } +Response: + Success: { + // Success response schema + } + Errors: { + // Error response schemas + } +Required Auth: Yes/No +\`\`\``; +}; + +// backend-implementation-prompt.ts +export const generateBackendImplementationPrompt = ( + backendOverview: string, + language: string, + framework: string, +): string => { + return `You are a Senior Backend Architect specializing in ${language} with ${framework}. Based on the provided Backend Overview, generate detailed implementation requirements for security, error handling, and other technical aspects. + +Backend Overview: +${backendOverview} + +Generate detailed implementation requirements following these sections: + +Your reply must start with: "\`\`\`BackendImplementation" and end with "\`\`\`". + +#### 3. Implementation Details +For each major component: +- **Request Handlers/Controllers** + - Implementation approach + - Request processing flow + - Response formatting + - Middleware integration + +- **Business Logic Layer/Services** + - Service patterns + - Business rule implementation + - External service integration + - Transaction management + +- **Data Access Layer** + - Database interaction patterns + - Query optimization + - Data mapping strategy + - Cache integration + +- **Middleware Components** + - Authentication middleware + - Validation middleware + - Logging middleware + - Error handling middleware + +#### 4. Security Implementation +- Authentication strategy + - Token management + - Session handling + - Refresh token mechanism +- Authorization rules + - Role-based access control + - Permission management + - Resource ownership +- Input validation + - Request validation + - Data sanitization +- API security + - Rate limiting + - CORS configuration + - Security headers +- Data protection + - Encryption methods + - Secure storage + - PII handling + +#### 5. Error Handling +- Error handling strategy + - Global error handler + - Domain-specific errors + - Operational errors +- Error response format + - Error codes + - Error messages + - Debug information +- Error types and codes + - HTTP status codes + - Application error codes + - Validation errors +- Logging strategy + - Log levels + - Log format + - Log storage + +Focus on: +1. ${language} and ${framework} specific implementation patterns +2. Best practices for each component +3. Security considerations +4. Error handling and logging +5. Performance optimization`; +};