-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapiCreatorService.js
More file actions
282 lines (231 loc) · 7.69 KB
/
Copy pathapiCreatorService.js
File metadata and controls
282 lines (231 loc) · 7.69 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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/**
* VibeDev Create API — deterministic scaffolds (no AI key required).
* framework: 'fastapi' | 'express'
* options: { name, routes: string[], withAuth?: boolean }
*/
export function createApiProject({ framework = 'fastapi', name = 'my-api', routes = ['items'], withAuth = false } = {}) {
const safe = (name || 'my-api').toLowerCase().replace(/[^a-z0-9-_]/g, '-').replace(/-+/g, '-') || 'my-api';
const resource = (routes[0] || 'items').toLowerCase().replace(/[^a-z0-9_]/g, '_') || 'items';
if (framework === 'express') return buildExpress(safe, resource, withAuth);
return buildFastApi(safe, resource, withAuth);
}
function buildFastApi(name, resource, withAuth) {
const files = [];
files.push({
path: 'requirements.txt',
content: 'fastapi==0.115.0\nuvicorn[standard]==0.30.6\npydantic==2.8.2\npython-multipart==0.0.9\n'
});
files.push({
path: 'README.md',
content: `# ${name}\n\nFastAPI app generated by VibeDev Create API.\n\n## Run locally\n\n\`\`\`bash\npython -m venv .venv\nsource .venv/bin/activate # Windows: .venv\\Scripts\\activate\npip install -r requirements.txt\nuvicorn app.main:app --reload --port 8000\n\`\`\`\n\nOpen http://127.0.0.1:8000/docs\n\n## Deploy free\n\n- **Render**: New → Web Service → this repo → start: \`uvicorn app.main:app --host 0.0.0.0 --port $PORT\`\n- Or use included \`render.yaml\`\n`
});
files.push({
path: 'app/main.py',
content: `from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.routes import ${resource}${withAuth ? ', auth' : ''}
app = FastAPI(title="${name}", version="1.0.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(${resource}.router, prefix="/api/${resource}", tags=["${resource}"])
${withAuth ? 'app.include_router(auth.router, prefix="/api/auth", tags=["auth"])' : ''}
@app.get("/health")
def health():
return {"status": "ok", "service": "${name}"}
`
});
files.push({
path: 'app/__init__.py',
content: ''
});
files.push({
path: 'app/routes/__init__.py',
content: ''
});
files.push({
path: `app/routes/${resource}.py`,
content: `from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Dict, List
router = APIRouter()
class ${capitalize(resource)}In(BaseModel):
name: str
description: str = ""
class ${capitalize(resource)}Out(${capitalize(resource)}In):
id: int
_db: Dict[int, ${capitalize(resource)}Out] = {}
_next = 1
@router.get("/", response_model=List[${capitalize(resource)}Out])
def list_all():
return list(_db.values())
@router.post("/", response_model=${capitalize(resource)}Out, status_code=201)
def create(body: ${capitalize(resource)}In):
global _next
item = ${capitalize(resource)}Out(id=_next, **body.model_dump())
_db[_next] = item
_next += 1
return item
@router.get("/{item_id}", response_model=${capitalize(resource)}Out)
def get_one(item_id: int):
if item_id not in _db:
raise HTTPException(404, "Not found")
return _db[item_id]
@router.delete("/{item_id}", status_code=204)
def delete_one(item_id: int):
if item_id not in _db:
raise HTTPException(404, "Not found")
del _db[item_id]
`
});
if (withAuth) {
files.push({
path: 'app/routes/auth.py',
content: `from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
router = APIRouter()
class LoginIn(BaseModel):
email: str
password: str
@router.post("/login")
def login(body: LoginIn):
# Demo only — replace with real auth
if not body.email or not body.password:
raise HTTPException(400, "email and password required")
return {"token": "demo-token", "email": body.email}
@router.get("/me")
def me():
return {"email": "demo@example.com", "role": "user"}
`
});
}
files.push({
path: 'render.yaml',
content: `services:
- type: web
name: ${name}
runtime: python
buildCommand: pip install -r requirements.txt
startCommand: uvicorn app.main:app --host 0.0.0.0 --port $PORT
plan: free
`
});
files.push({
path: 'Dockerfile',
content: `FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
`
});
return { framework: 'fastapi', name, files, runHint: 'uvicorn app.main:app --reload --port 8000', docsUrl: 'http://127.0.0.1:8000/docs' };
}
function buildExpress(name, resource, withAuth) {
const files = [];
files.push({
path: 'package.json',
content: JSON.stringify({
name,
version: '1.0.0',
type: 'module',
scripts: { start: 'node src/index.js', dev: 'node --watch src/index.js' },
dependencies: { express: '^4.19.2', cors: '^2.8.5' }
}, null, 2)
});
files.push({
path: 'README.md',
content: `# ${name}\n\nExpress API generated by VibeDev Create API.\n\n## Run\n\n\`\`\`bash\nnpm install\nnpm run dev\n\`\`\`\n\nHealth: http://127.0.0.1:3000/health\n\n## Deploy free\n\nRender Web Service → \`npm start\` or use \`render.yaml\`\n`
});
files.push({
path: 'src/index.js',
content: `import express from 'express';
import cors from 'cors';
import { ${resource}Router } from './routes/${resource}.js';
${withAuth ? "import { authRouter } from './routes/auth.js';" : ''}
const app = express();
app.use(cors());
app.use(express.json());
app.get('/health', (_req, res) => res.json({ status: 'ok', service: '${name}' }));
app.use('/api/${resource}', ${resource}Router);
${withAuth ? "app.use('/api/auth', authRouter);" : ''}
const port = process.env.PORT || 3000;
app.listen(port, () => console.log('${name} on http://127.0.0.1:' + port));
`
});
files.push({
path: `src/routes/${resource}.js`,
content: `import { Router } from 'express';
export const ${resource}Router = Router();
const db = new Map();
let nextId = 1;
${resource}Router.get('/', (_req, res) => {
res.json([...db.values()]);
});
${resource}Router.post('/', (req, res) => {
const { name = '', description = '' } = req.body || {};
const item = { id: nextId++, name, description };
db.set(item.id, item);
res.status(201).json(item);
});
${resource}Router.get('/:id', (req, res) => {
const item = db.get(Number(req.params.id));
if (!item) return res.status(404).json({ error: 'Not found' });
res.json(item);
});
${resource}Router.delete('/:id', (req, res) => {
if (!db.has(Number(req.params.id))) return res.status(404).json({ error: 'Not found' });
db.delete(Number(req.params.id));
res.status(204).end();
});
`
});
if (withAuth) {
files.push({
path: 'src/routes/auth.js',
content: `import { Router } from 'express';
export const authRouter = Router();
authRouter.post('/login', (req, res) => {
const { email, password } = req.body || {};
if (!email || !password) return res.status(400).json({ error: 'email and password required' });
res.json({ token: 'demo-token', email });
});
authRouter.get('/me', (_req, res) => {
res.json({ email: 'demo@example.com', role: 'user' });
});
`
});
}
files.push({
path: 'render.yaml',
content: `services:
- type: web
name: ${name}
runtime: node
buildCommand: npm install
startCommand: npm start
plan: free
`
});
files.push({
path: 'Dockerfile',
content: `FROM node:22-alpine
WORKDIR /app
COPY package.json .
RUN npm install --omit=dev
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
`
});
return { framework: 'express', name, files, runHint: 'npm install && npm run dev', docsUrl: 'http://127.0.0.1:3000/health' };
}
function capitalize(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
export default { createApiProject };