forked from Prompt-Hash-Stellar/prompt-hash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
84 lines (74 loc) · 2.57 KB
/
Copy pathindex.ts
File metadata and controls
84 lines (74 loc) · 2.57 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
import { withObservability } from "../../src/lib/observability/wrapper";
import connectDb from "../../server/src/db/connectDb";
import WebhookSubscription from "../../server/src/models/WebhookSubscription";
import { ALLOWED_EVENTS } from "../../server/src/services/webhookDispatcher";
import { randomBytes } from "crypto";
async function handler(req: any, res: any) {
await connectDb();
if (req.method === "GET") {
const { walletAddress } = req.query ?? {};
if (!walletAddress) {
res.status(400).json({ error: "walletAddress query param is required." });
return;
}
const sub = await WebhookSubscription.findOne({
walletAddress: String(walletAddress).toLowerCase(),
}).select("-secret");
if (!sub) {
res.status(404).json({ error: "No webhook registered for this wallet." });
return;
}
res.status(200).json(sub);
return;
}
if (req.method === "POST") {
const { walletAddress, url, events } = req.body ?? {};
if (!walletAddress || !url) {
res.status(400).json({ error: "walletAddress and url are required." });
return;
}
try {
new URL(url);
} catch {
res.status(400).json({ error: "url must be a valid URL." });
return;
}
const secret = randomBytes(32).toString("hex");
const resolvedEvents = Array.isArray(events)
? events.filter((e: string) => ALLOWED_EVENTS.includes(e as any))
: ["PromptPurchased"];
const existing = await WebhookSubscription.findOne({
walletAddress: String(walletAddress).toLowerCase(),
});
if (existing) {
existing.url = url;
existing.events = resolvedEvents;
existing.active = true;
existing.failureCount = 0;
await existing.save();
res.status(200).json({ message: "Webhook updated.", id: existing._id, secret });
return;
}
const sub = new WebhookSubscription({
walletAddress: String(walletAddress).toLowerCase(),
url,
secret,
events: resolvedEvents,
});
await sub.save();
res.status(201).json({ message: "Webhook registered.", id: sub._id, secret });
return;
}
if (req.method === "DELETE") {
const { walletAddress } = req.body ?? {};
if (!walletAddress) {
res.status(400).json({ error: "walletAddress is required." });
return;
}
await WebhookSubscription.deleteOne({ walletAddress: String(walletAddress).toLowerCase() });
res.status(200).json({ message: "Webhook removed." });
return;
}
res.status(405).json({ error: "Method not allowed." });
}
export default withObservability(handler, "webhooks");