forked from CalloraOrg/Callora-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.ts
More file actions
253 lines (218 loc) · 7.99 KB
/
Copy pathapp.ts
File metadata and controls
253 lines (218 loc) · 7.99 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
import express from 'express';
import cors from 'cors';
import {
InMemoryUsageEventsRepository,
type GroupBy,
type UsageEventsRepository,
} from './repositories/usageEventsRepository.js';
import { defaultApiRepository, type ApiRepository } from './repositories/apiRepository.js';
import { defaultDeveloperRepository, type DeveloperRepository } from './repositories/developerRepository.js';
import { apiStatusEnum, type ApiStatus } from './db/schema.js';
import type { ApiRepository } from './repositories/apiRepository.js';
import { requireAuth, type AuthenticatedLocals } from './middleware/requireAuth.js';
import { buildDeveloperAnalytics } from './services/developerAnalytics.js';
import { errorHandler } from './middleware/errorHandler.js';
import { requestIdMiddleware } from './middleware/requestId.js';
import { requestLogger } from './middleware/logging.js';
interface AppDependencies {
usageEventsRepository: UsageEventsRepository;
apiRepository: ApiRepository;
developerRepository: DeveloperRepository;
}
const isValidGroupBy = (value: string): value is GroupBy =>
value === 'day' || value === 'week' || value === 'month';
const parseDate = (value: unknown): Date | null => {
if (typeof value !== 'string') {
return null;
}
const date = new Date(value);
if (Number.isNaN(date.getTime())) {
return null;
}
return date;
};
const parseNonNegativeIntegerParam = (
value: unknown
): { value?: number; invalid: boolean } => {
if (typeof value !== 'string' || value.trim() === '') {
return { value: undefined, invalid: false };
}
const parsed = Number(value);
if (!Number.isFinite(parsed) || parsed < 0 || !Number.isInteger(parsed)) {
return { value: undefined, invalid: true };
}
return { value: parsed, invalid: false };
};
export const createApp = (dependencies?: Partial<AppDependencies>) => {
const app = express();
const usageEventsRepository =
dependencies?.usageEventsRepository ?? new InMemoryUsageEventsRepository();
const apiRepository = dependencies?.apiRepository ?? defaultApiRepository;
const developerRepository = dependencies?.developerRepository ?? defaultDeveloperRepository;
app.use(requestIdMiddleware);
// Lazy singleton for production Drizzle repo; injected repo is used in tests.
const _injectedApiRepo = dependencies?.apiRepository;
let _drizzleApiRepo: ApiRepository | undefined;
async function getApiRepo(): Promise<ApiRepository> {
if (_injectedApiRepo) return _injectedApiRepo;
if (!_drizzleApiRepo) {
const { DrizzleApiRepository } = await import('./repositories/apiRepository.drizzle.js');
_drizzleApiRepo = new DrizzleApiRepository();
}
return _drizzleApiRepo;
}
app.use(requestLogger);
const allowedOrigins = (process.env.CORS_ALLOWED_ORIGINS ?? 'http://localhost:5173')
.split(',')
.map((o) => o.trim());
app.use(
cors({
origin(origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
methods: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
}),
);
app.use(express.json());
app.get('/api/health', (_req, res) => {
res.json({ status: 'ok', service: 'callora-backend' });
});
app.get('/api/apis', (_req, res) => {
res.json({ apis: [] });
});
app.get('/api/apis/:id', async (req, res) => {
const rawId = req.params.id;
const id = Number(rawId);
if (!Number.isInteger(id) || id <= 0) {
res.status(400).json({ error: 'id must be a positive integer' });
return;
}
const apiRepo = await getApiRepo();
const api = await apiRepo.findById(id);
if (!api) {
res.status(404).json({ error: 'API not found or not active' });
return;
}
const endpoints = await apiRepo.getEndpoints(id);
res.json({
id: api.id,
name: api.name,
description: api.description,
base_url: api.base_url,
logo_url: api.logo_url,
category: api.category,
status: api.status,
developer: api.developer,
endpoints: endpoints.map((ep) => ({
path: ep.path,
method: ep.method,
price_per_call_usdc: ep.price_per_call_usdc,
description: ep.description,
})),
});
});
app.get('/api/usage', (_req, res) => {
res.json({ calls: 0, period: 'current' });
});
app.get('/api/developers/apis', requireAuth, async (req, res: express.Response<unknown, AuthenticatedLocals>) => {
const user = res.locals.authenticatedUser;
if (!user) {
res.status(401).json({ error: 'Unauthorized' });
return;
}
const developer = await developerRepository.findByUserId(user.id);
if (!developer) {
res.status(404).json({ error: 'Developer profile not found' });
return;
}
const statusParam = typeof req.query.status === 'string' ? req.query.status : undefined;
let statusFilter: ApiStatus | undefined;
if (statusParam) {
if (!apiStatusEnum.includes(statusParam as ApiStatus)) {
res
.status(400)
.json({ error: `status must be one of: ${apiStatusEnum.join(', ')}` });
return;
}
statusFilter = statusParam as ApiStatus;
}
const limitParam = parseNonNegativeIntegerParam(req.query.limit);
if (limitParam.invalid) {
res.status(400).json({ error: 'limit must be a non-negative integer' });
return;
}
const offsetParam = parseNonNegativeIntegerParam(req.query.offset);
if (offsetParam.invalid) {
res.status(400).json({ error: 'offset must be a non-negative integer' });
return;
}
const apis = await apiRepository.listByDeveloper(developer.id, {
status: statusFilter,
...(typeof limitParam.value === 'number' ? { limit: limitParam.value } : {}),
...(typeof offsetParam.value === 'number' ? { offset: offsetParam.value } : {}),
});
const usageStats = await usageEventsRepository.aggregateByDeveloper(user.id);
const statsByApi = new Map(usageStats.map((stat) => [stat.apiId, stat]));
const payload = apis.map((api) => {
const stats = statsByApi.get(String(api.id));
const entry: { id: number; name: string; status: ApiStatus; callCount: number; revenue?: string } = {
id: api.id,
name: api.name,
status: api.status,
callCount: stats?.calls ?? 0,
};
if (stats) {
entry.revenue = stats.revenue.toString();
}
return entry;
});
res.json({ data: payload });
});
app.get('/api/developers/analytics', requireAuth, async (req, res: express.Response<unknown, AuthenticatedLocals>) => {
const user = res.locals.authenticatedUser;
if (!user) {
res.status(401).json({ error: 'Unauthorized' });
return;
}
const groupBy = req.query.groupBy ?? 'day';
if (typeof groupBy !== 'string' || !isValidGroupBy(groupBy)) {
res.status(400).json({ error: 'groupBy must be one of: day, week, month' });
return;
}
const from = parseDate(req.query.from);
const to = parseDate(req.query.to);
if (!from || !to) {
res.status(400).json({ error: 'from and to are required ISO date values' });
return;
}
if (from > to) {
res.status(400).json({ error: 'from must be before or equal to to' });
return;
}
const apiId = typeof req.query.apiId === 'string' ? req.query.apiId : undefined;
if (apiId) {
const ownsApi = await usageEventsRepository.developerOwnsApi(user.id, apiId);
if (!ownsApi) {
res.status(403).json({ error: 'Forbidden: API does not belong to authenticated developer' });
return;
}
}
const includeTop = req.query.includeTop === 'true';
const events = await usageEventsRepository.findByDeveloper({
developerId: user.id,
from,
to,
apiId,
});
const analytics = buildDeveloperAnalytics(events, groupBy, includeTop);
res.json(analytics);
});
app.use(errorHandler);
return app;
};