-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
174 lines (148 loc) · 5.46 KB
/
Copy pathserver.ts
File metadata and controls
174 lines (148 loc) · 5.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import { GoogleGenAI } from '@google/genai';
import apiRouter from './src/server/routes/index';
import { errorHandler } from './src/server/middlewares/errorHandler';
import { securityHeaders } from './src/server/middlewares/security';
import { rateLimiter } from './src/server/middlewares/rateLimiter';
import { logger } from './src/server/utils/logger';
import { printStartupBanner } from './src/server/utils/envValidator';
import { telemetry } from './src/server/utils/monitoring';
const currentDirname = process.cwd();
async function startServer() {
const app = express();
const PORT = Number(process.env.PORT) || 3000;
// 1. Core Production Middlewares
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
app.use(securityHeaders);
app.use(rateLimiter(300, 60000)); // 300 requests per min
// Initialize Gemini AI client lazily
const getGeminiClient = () => {
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
throw new Error('GEMINI_API_KEY environment variable is missing.');
}
return new GoogleGenAI({ apiKey });
};
// 2. Mount Versioned REST API Routes (/api/v1)
app.use('/api/v1', apiRouter);
// Production health check & telemetry probe
app.get('/api/health', (_req, res) => {
const diagnostics = telemetry.getSystemDiagnostics();
res.json({
status: 'ok',
service: 'MobileSQL Express Backend',
version: '1.0.0-prod',
timestamp: new Date().toISOString(),
diagnostics,
});
});
// 3. AI Copilot: Query Explanation Endpoint
app.post('/api/copilot/explain', async (req, res, next) => {
try {
const { sql, schemaContext, dialect = 'PostgreSQL' } = req.body;
if (!sql) {
return res.status(400).json({ success: false, error: 'SQL query is required.' });
}
const ai = getGeminiClient();
const prompt = `
You are the MobileSQL Senior Database Architect Copilot.
Explain the following ${dialect} SQL query for a database learner.
Keep explanations concise, structured, and easy to read on a mobile screen.
Context Schema:
${schemaContext ? JSON.stringify(schemaContext, null, 2) : 'Default E-Commerce Schema'}
Query to Explain:
\`\`\`sql
${sql}
\`\`\`
Provide output in JSON format with fields:
- "summary": One-sentence high-level summary of what the query achieves
- "breakdown": Array of key SQL operations (e.g. JOIN type, WHERE filtering, GROUP BY aggregation)
- "performanceTip": One actionable performance tip or indexing advice
`;
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: prompt,
config: {
responseMimeType: 'application/json',
},
});
const responseText = response.text;
const parsed = responseText ? JSON.parse(responseText) : {};
return res.json({ success: true, data: parsed });
} catch (error) {
next(error);
}
});
// 4. AI Copilot: Natural Language to SQL Endpoint
app.post('/api/copilot/generate', async (req, res, next) => {
try {
const { userPrompt, schemaContext, dialect = 'PostgreSQL' } = req.body;
if (!userPrompt) {
return res.status(400).json({ success: false, error: 'Prompt is required.' });
}
const ai = getGeminiClient();
const systemInstruction = `
You are MobileSQL Copilot, an expert SQL query generator for ${dialect}.
Convert the user's natural language request into clean, efficient, standard SQL.
Available Schema:
${schemaContext ? JSON.stringify(schemaContext, null, 2) : 'Default E-Commerce Schema (users, orders, products, order_items)'}
Format response in JSON with:
- "sql": The exact executable SQL string
- "explanation": Brief explanation of how the query works
- "estimatedComplexity": "Low" | "Medium" | "High"
`;
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: userPrompt,
config: {
systemInstruction,
responseMimeType: 'application/json',
},
});
const parsed = response.text ? JSON.parse(response.text) : {};
return res.json({ success: true, data: parsed });
} catch (error) {
next(error);
}
});
// 5. 404 Handler for Unmatched API Routes
app.all('/api/*', (req, res) => {
res.status(404).json({
success: false,
error: `API endpoint ${req.method} ${req.originalUrl} not found.`,
timestamp: new Date().toISOString(),
});
});
// 6. Global Error Handling Middleware
app.use(errorHandler);
// 7. Vite Dev Server Integration vs Production Static File Serving
if (process.env.NODE_ENV !== 'production') {
const { createServer: createViteServer } = await import('vite');
const isHmrDisabled = process.env.DISABLE_HMR === 'true';
const vite = await createViteServer({
server: {
middlewareMode: true,
hmr: isHmrDisabled ? false : undefined,
watch: isHmrDisabled ? null : {},
},
appType: 'spa',
});
app.use(vite.middlewares);
} else {
const distPath = path.join(process.cwd(), 'dist');
app.use(express.static(distPath));
app.get('*', (_req, res) => {
res.sendFile(path.join(distPath, 'index.html'));
});
}
app.listen(PORT, '0.0.0.0', () => {
printStartupBanner(PORT);
});
}
startServer().catch((err) => {
logger.error('[MobileSQL Server Fatal Error]', err);
process.exit(1);
});