Skip to content

Commit 7195e06

Browse files
committed
backend support for build system
1 parent 44f21d9 commit 7195e06

File tree

13 files changed

+1297
-361
lines changed

13 files changed

+1297
-361
lines changed

backend/src/build-system/handlers/backend/code-generate/index.ts

Lines changed: 336 additions & 21 deletions
Large diffs are not rendered by default.

backend/src/build-system/handlers/backend/code-generate/prompt.ts

Lines changed: 101 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,14 @@
11
export const generateBackendCodePrompt = (
22
projectName: string,
3-
sitemapDoc: string,
4-
datamapDoc: string,
5-
backendRequirementDoc: string,
63
databaseType: string,
7-
databaseSchemas: string,
84
currentFile: string,
9-
fileType: string = 'javascript',
5+
fileType: string = 'Javascript',
106
dependencyFile: string,
117
): string => {
128
const defaultDependencies = {
13-
sqlite3: '^5.1.6',
14-
express: '^4.18.2',
9+
sqlite3: '^5',
10+
express: '^4',
11+
jsonwebtoken: '^9',
1512
};
1613

1714
// Parse dependency file if provided, otherwise use defaults
@@ -25,24 +22,16 @@ export const generateBackendCodePrompt = (
2522
dependencies = defaultDependencies;
2623
}
2724

28-
return `You are an expert backend developer.
29-
Your task is to generate a complete backend codebase within a single file for a project named "${projectName}". The code should be written using the Express framework with ES Module syntax (using \`import\` statements), and the database is ${databaseType}. The code must be written in \`${fileType}\`. The backend code should be scalable, maintainable, and adhere to best practices.
30-
25+
return `Role: You are an expert backend developer.
26+
Task: Your task is to generate a complete backend codebase within a single file for a project named "${projectName}". The code should be written using the Express framework with ES Module syntax (using \`import\` statements), and the database is ${databaseType}. The code must be written in \`${fileType}\`. The backend code should be scalable, maintainable, and adhere to best practices.
27+
Current File: ${currentFile}.
28+
3129
### Project Dependencies
3230
The project uses the following dependencies:
3331
\`\`\`json
3432
${JSON.stringify(dependencies, null, 2)}
3533
\`\`\`
3634
37-
### Based on the following input:
38-
39-
- **Project Name:** ${projectName}
40-
- **Sitemap Documentation:** ${sitemapDoc}
41-
- **Data Analysis Document:** ${datamapDoc}
42-
- **Backend Requirements:** ${backendRequirementDoc}
43-
- **Database schemas:** These schemas are defined in \`./schema.sql\`. The code must read and execute this file during database initialization.
44-
- **Current Implementation:** ${currentFile || 'No existing implementation'}
45-
4635
### Backend Requirements Analysis:
4736
Based on the provided backend requirements document, ensure implementation of:
4837
- All specified API endpoints and their functionality
@@ -59,9 +48,10 @@ export const generateBackendCodePrompt = (
5948
**Include:**
6049
1. **Server Setup:**
6150
- Initialize the server using the Express framework with ES Module syntax (use \`import\` instead of \`require\`).
62-
- Configure middleware for JSON parsing and CORS.
51+
- Configure middleware for JSON parsing and CORS example "app.use(cors()); "
6352
6453
2. **Database Connection and Initialization:**
54+
Database schemas: These schemas are defined in \`./schema.sql\`. The code must read and execute this file during database initialization.
6555
For SQLite database initialization, you must include code to execute the ./schema.sql file. There are several approaches:
6656
6757
1. Using better-sqlite3:
@@ -103,29 +93,29 @@ export const generateBackendCodePrompt = (
10393
- Implement connection pooling if needed
10494
10595
3. **Implementation Guidelines for SQLite:**
106-
1. **Basic Database Operations:**
107-
\`\`\`${fileType}
108-
// Using sqlite3
109-
import sqlite3 from 'sqlite3';
110-
const db = new sqlite3.Database('./database.sqlite');
111-
112-
// Basic query example
113-
db.all("SELECT * FROM users", [], (err, rows) => {
114-
if (err) throw err;
115-
console.log(rows);
116-
});
117-
\`\`\`
118-
119-
2. **Performance-Critical Operations:**
120-
\`\`\`${fileType}
121-
// Using better-sqlite3
122-
import Database from 'better-sqlite3';
123-
const db = new Database('database.sqlite', { verbose: console.log });
124-
125-
// Prepared statement example
126-
const stmt = db.prepare('SELECT * FROM users WHERE id = ?');
127-
const user = stmt.get(userId);
128-
\`\`\`
96+
1. **Basic Database Operations:**
97+
\`\`\`${fileType}
98+
// Using sqlite3
99+
import sqlite3 from 'sqlite3';
100+
const db = new sqlite3.Database('./database.sqlite');
101+
102+
// Basic query example
103+
db.all("SELECT * FROM users", [], (err, rows) => {
104+
if (err) throw err;
105+
console.log(rows);
106+
});
107+
\`\`\`
108+
109+
2. **Performance-Critical Operations:**
110+
\`\`\`${fileType}
111+
// Using better-sqlite3
112+
import Database from 'better-sqlite3';
113+
const db = new Database('database.sqlite', { verbose: console.log });
114+
115+
// Prepared statement example
116+
const stmt = db.prepare('SELECT * FROM users WHERE id = ?');
117+
const user = stmt.get(userId);
118+
\`\`\`
129119
130120
4. **Route Definitions:**
131121
- Define RESTful API endpoints based on the sitemap documentation.
@@ -148,7 +138,7 @@ export const generateBackendCodePrompt = (
148138
7. **Environment Configuration:**
149139
- Use dotenv or similar for environment variables.
150140
- Database configuration should be environment-based.
151-
- Server port and other settings should be configurable.
141+
- Server port is 3000 and other settings should be configurable.
152142
153143
8. **Comments and Documentation:**
154144
- Add comments explaining each section and key code blocks.
@@ -163,10 +153,7 @@ export const generateBackendCodePrompt = (
163153
- Hardcoded configuration values.
164154
165155
**Special Requirements:**
166-
- Use environment variables for database path and server settings.
167-
- Implement proper statement preparation and parameter binding.
168156
- Ensure all database operations are wrapped in appropriate error handling.
169-
- Use proper TypeScript types and interfaces.
170157
- Implement proper logging throughout the application.
171158
172159
### Ask Yourself:
@@ -176,8 +163,73 @@ export const generateBackendCodePrompt = (
176163
4. Are transactions used appropriately for data consistency?
177164
5. Is the schema.sql file properly loaded and executed?
178165
6. Are all configurations properly externalized?
179-
7. Is the code properly typed with TypeScript?
180-
8. Is there adequate logging and error tracking?
166+
7. Is there adequate logging and error tracking?
167+
168+
### Output Format:
169+
170+
Provide the backend code within \`<GENERATE>\` tags as follows:
171+
172+
<GENERATE>
173+
// Your generated backend code goes here
174+
</GENERATE>
175+
`;
176+
};
177+
178+
export const generateForMultiFileBackendCodePrompt = (
179+
projectName: string,
180+
databaseType: string,
181+
currentFile: string,
182+
fileType: string = 'javascript',
183+
dependencyFile: string,
184+
): string => {
185+
const defaultDependencies = {
186+
sqlite3: '^5',
187+
express: '^4',
188+
};
189+
190+
// Parse dependency file if provided, otherwise use defaults
191+
// TODO: get dependencies info from embedding model
192+
let dependencies;
193+
try {
194+
dependencies = dependencyFile
195+
? JSON.parse(dependencyFile)
196+
: defaultDependencies;
197+
} catch (error) {
198+
dependencies = defaultDependencies;
199+
}
200+
201+
return `Role: You are an expert backend developer.
202+
Task: Your task is to generate a complete backend codebase using Express framework, database ${databaseType}, and language Javascript. The backend code should be scalable, maintainable, and adhere to best practices.
203+
Current File: ${currentFile}.
204+
205+
## Project External Dependencies
206+
The project uses the following dependencies:
207+
\`\`\`json
208+
${JSON.stringify(dependencies, null, 2)}
209+
\`\`\`
210+
211+
212+
213+
### Instructions and Rules:
214+
1. Implement Only One file: Implement only the file specified in "Current File" - do not generate code for multiple files.
215+
2. COMPLETE CODE: Your code will be part of the entire project, so please implement complete, reliable, reusable code with no TODOs or placeholders.
216+
3. ES Module Syntax: Use ES Module syntax (import/export) consistently throughout the code.
217+
4. File Structure and Dependencies: The current file might depend on other files in the project use the Project Internal Dependencies to help you.
218+
5. CAREFULLY CHECK:
219+
- Before importing a file, verify that the file should logically exist
220+
- Ensure that you haven't missed any internal dependencies import
221+
6. Error Handling: Implement comprehensive error handling for database operations, API calls, and all async operations.
222+
7. Database Specific: For ${databaseType}, ensure you're using appropriate connection methods and query formats.
223+
8. Configuration: Use environment variables for sensitive values and configuration (use process.env)
224+
9. RESTful Standards: When implementing controllers and routes, follow RESTful API standards.
225+
10. Documentation: Include JSDoc comments for functions and important code sections.
226+
11. Logging: Implement appropriate logging for errors and significant operations.
227+
12. Schema Init: For database files, ensure proper initialization of tables and schemas if needed.
228+
229+
### Ask Yourself:
230+
1. Are all configurations properly externalized?
231+
2. Is the code properly typed with TypeScript?
232+
3. Is there adequate logging and error tracking?
181233
182234
### Output Format:
183235

backend/src/build-system/handlers/backend/file-review/file-review.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,7 @@ export class BackendFileReviewHandler implements BuildHandler<string> {
4444
project description: ${description},
4545
`;
4646

47-
const backendRequirement = context.getNodeData(
48-
BackendRequirementHandler,
49-
)?.overview;
47+
const backendRequirement = context.getNodeData(BackendRequirementHandler);
5048
const backendCode = [context.getNodeData(BackendCodeHandler)];
5149

5250
if (!backendRequirement) {

backend/src/build-system/handlers/backend/requirements-document/index.ts

Lines changed: 39 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ import { chatSyncWithClocker } from 'src/build-system/utils/handler-helper';
1111
import { BuildNode, BuildNodeRequire } from 'src/build-system/hanlder-manager';
1212
import { DBRequirementHandler } from '../../database/requirements-document';
1313
import { UXDMDHandler } from '../../ux/datamap';
14-
import { UXSMDHandler } from '../../ux/sitemap-document';
14+
import { DBSchemaHandler } from '../../database/schemas/schemas';
15+
import { MessageInterface } from 'src/common/model-provider/types';
1516

1617
type BackendRequirementResult = {
1718
overview: string;
@@ -29,15 +30,11 @@ type BackendRequirementResult = {
2930
*/
3031

3132
@BuildNode()
32-
@BuildNodeRequire([DBRequirementHandler, UXDMDHandler, UXSMDHandler])
33-
export class BackendRequirementHandler
34-
implements BuildHandler<BackendRequirementResult>
35-
{
33+
@BuildNodeRequire([DBRequirementHandler, UXDMDHandler, DBSchemaHandler])
34+
export class BackendRequirementHandler implements BuildHandler<string> {
3635
private readonly logger: Logger = new Logger('BackendRequirementHandler');
3736

38-
async run(
39-
context: BuilderContext,
40-
): Promise<BuildResult<BackendRequirementResult>> {
37+
async run(context: BuilderContext): Promise<BuildResult<string>> {
4138
this.logger.log('Generating Backend Requirements Document...');
4239

4340
const language = context.getGlobalContext('language') || 'javascript';
@@ -48,35 +45,60 @@ export class BackendRequirementHandler
4845

4946
const dbRequirements = context.getNodeData(DBRequirementHandler);
5047
const datamapDoc = context.getNodeData(UXDMDHandler);
51-
const sitemapDoc = context.getNodeData(UXSMDHandler);
48+
const dbSchema = context.getNodeData(DBSchemaHandler);
5249

53-
if (!dbRequirements || !datamapDoc || !sitemapDoc) {
50+
if (!dbRequirements || !datamapDoc || !dbSchema) {
5451
this.logger.error(
55-
'Missing required parameters: dbRequirements, datamapDoc, or sitemapDoc',
52+
'Missing required parameters: dbRequirements, datamapDoc, or dbSchema',
5653
);
5754
throw new MissingConfigurationError(
58-
'Missing required parameters: dbRequirements, datamapDoc, or sitemapDoc.',
55+
'Missing required parameters: dbRequirements, datamapDoc, or dbSchema.',
5956
);
6057
}
6158

6259
const overviewPrompt = generateBackendOverviewPrompt(
6360
projectName,
64-
dbRequirements,
65-
datamapDoc,
66-
sitemapDoc,
6761
language,
6862
framework,
6963
packages,
7064
);
7165

66+
const messages = [
67+
{
68+
role: 'system' as const,
69+
content: overviewPrompt,
70+
},
71+
{
72+
role: 'user' as const,
73+
content: `## Database Requirements:
74+
${dbRequirements}
75+
`,
76+
},
77+
{
78+
role: 'user' as const,
79+
content: `## DataBase Schema:
80+
${dbSchema}
81+
`,
82+
},
83+
{
84+
role: 'user' as const,
85+
content: `## Frontend Data Requirements:
86+
${datamapDoc} `,
87+
},
88+
{
89+
role: 'user',
90+
content: `Now you can provide the code, don't forget the <GENERATE></GENERATE> tags. Do not be lazy.`,
91+
},
92+
] as MessageInterface[];
93+
7294
let backendOverview: string;
7395

7496
try {
7597
backendOverview = await chatSyncWithClocker(
7698
context,
7799
{
78100
model: 'gpt-4o-mini',
79-
messages: [{ content: overviewPrompt, role: 'system' }],
101+
messages: messages,
80102
},
81103
'generateBackendOverviewPrompt',
82104
BackendRequirementHandler.name,
@@ -88,15 +110,7 @@ export class BackendRequirementHandler
88110
// Return generated data
89111
return {
90112
success: true,
91-
data: {
92-
overview: removeCodeBlockFences(backendOverview),
93-
implementation: '', // Implementation generation skipped
94-
config: {
95-
language,
96-
framework,
97-
packages,
98-
},
99-
},
113+
data: removeCodeBlockFences(backendOverview),
100114
};
101115
}
102116
}

0 commit comments

Comments
 (0)