-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmiddleware-usage.ts
More file actions
106 lines (89 loc) · 2.5 KB
/
Copy pathmiddleware-usage.ts
File metadata and controls
106 lines (89 loc) · 2.5 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
import express from "express";
import { biller } from "./scrawn/biller.ts";
const app = express();
app.use(express.json());
app.use(
biller.middlewareEventConsumer({
extractor: (req) => ({
userId: (req.headers?.["x-user-id"] as string) || "anonymous",
debit: req.body?.cost || 1,
}),
blacklist: ["/api/collect-payment", "/api/status"],
})
);
// API Routes
app.post("/api/generate", (req, res) => {
const { prompt } = req.body;
const result = `Generated content for: ${prompt}`;
res.json({
success: true,
result,
billed: req.body?.cost || 1,
});
});
app.post("/api/analyze", (req, res) => {
const { data } = req.body;
const analysis = {
itemCount: data?.length || 0,
summary: "Analysis complete",
};
res.json({
success: true,
analysis,
billed: req.body?.cost || 1,
});
});
app.post("/api/translate", (req, res) => {
const { text, targetLang } = req.body;
const translated = `[${targetLang}] ${text}`;
res.json({
success: true,
translated,
billed: req.body?.cost || 1,
});
});
app.get("/api/status", (req, res) => {
res.json({
status: "ok",
message: "Server is running",
});
});
app.post("/api/collect-payment", async (req, res) => {
try {
const { userId } = req.body;
if (!userId) {
return res.status(400).json({
success: false,
error: "userId is required",
});
}
const checkoutLink = await biller.collectPayment(userId);
res.redirect(checkoutLink);
} catch (error) {
console.error("Failed to collect payment:", error);
res.status(500).json({
success: false,
error:
error instanceof Error
? error.message
: "Failed to create checkout link",
});
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(
`Scrawn tracking enabled on all endpoints (except /api/collect-payment)`
);
console.log(`\nTry it out:`);
console.log(`\nTrack an event:`);
console.log(`curl -X POST http://localhost:${PORT}/api/generate \\`);
console.log(` -H "Content-Type: application/json" \\`);
console.log(` -H "x-user-id: user_123" \\`);
console.log(` -d '{"prompt": "Hello world", "cost": 5}'`);
console.log(`\nCollect payment (redirects to checkout):`);
console.log(`curl -X POST http://localhost:${PORT}/api/collect-payment \\`);
console.log(` -H "Content-Type: application/json" \\`);
console.log(` -d '{"userId": "user_123"}'`);
});