Skip to content

Commit

Permalink
feat: Add BackendRequirementHandler for generating Backend Requiremen…
Browse files Browse the repository at this point in the history
…ts 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 <[email protected]>
  • Loading branch information
Sma1lboy committed Nov 17, 2024
1 parent 0fd40d4 commit 4b18067
Show file tree
Hide file tree
Showing 2 changed files with 239 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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<BuildResult> {
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<string, string>;
};

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,
},
},
};
}
}
165 changes: 165 additions & 0 deletions backend/src/build-system/node/backend-requirements-document/prompt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
// backend-overview-prompt.ts
export const generateBackendOverviewPrompt = (
projectName: string,
dbRequirements: string,
language: string,
framework: string,
packages: Record<string, string>,
): 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`;
};

0 comments on commit 4b18067

Please sign in to comment.