forked from KCEE0901/trustchain-escrow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhookController.js
More file actions
96 lines (80 loc) · 2.32 KB
/
Copy pathwebhookController.js
File metadata and controls
96 lines (80 loc) · 2.32 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
import webhookService from '../../services/webhookService.js';
const MAX_EVENT_TYPES = 20;
const ALLOWED_SCHEMES = ['https:'];
function isValidWebhookUrl(raw) {
try {
const parsed = new URL(raw);
return ALLOWED_SCHEMES.includes(parsed.protocol);
} catch {
return false;
}
}
const subscribe = async (req, res) => {
try {
const { url, eventTypes } = req.body;
if (!url || !isValidWebhookUrl(url)) {
return res.status(400).json({ error: 'url must be a valid HTTPS URL' });
}
if (!Array.isArray(eventTypes) || eventTypes.length === 0) {
return res.status(400).json({ error: 'eventTypes must be a non-empty array' });
}
if (eventTypes.length > MAX_EVENT_TYPES) {
return res
.status(400)
.json({ error: `eventTypes may not exceed ${MAX_EVENT_TYPES} entries` });
}
const result = await webhookService.createSubscription({
url,
eventTypes: eventTypes.slice(0, MAX_EVENT_TYPES),
createdBy: req.user?.address || null,
});
res.status(201).json({ data: result });
} catch (err) {
res.status(500).json({ error: err.message });
}
};
const listSubscriptions = async (req, res) => {
try {
const subscriptions = await webhookService.listSubscriptions({
createdBy: req.user?.address || null,
});
res.json({ data: subscriptions });
} catch (err) {
res.status(500).json({ error: err.message });
}
};
const deleteSubscription = async (req, res) => {
try {
const deleted = await webhookService.deleteSubscription({
id: req.params.id,
createdBy: req.user?.address || null,
});
if (!deleted) {
return res.status(404).json({ error: 'Webhook subscription not found' });
}
res.status(204).send();
} catch (err) {
res.status(500).json({ error: err.message });
}
};
const getDeliveries = async (req, res) => {
try {
const page = Number(req.query.page || 1);
const limit = Math.min(Number(req.query.limit || 30), 100);
const result = await webhookService.getDeliveryHistory({
subscriptionId: req.params.id,
createdBy: req.user?.address || null,
page,
limit,
});
res.json(result);
} catch (err) {
res.status(500).json({ error: err.message });
}
};
export default {
subscribe,
listSubscriptions,
deleteSubscription,
getDeliveries,
};