forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhookRepository.js
More file actions
152 lines (135 loc) · 4.42 KB
/
Copy pathwebhookRepository.js
File metadata and controls
152 lines (135 loc) · 4.42 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
const { query } = require('./index');
// ---------------------------------------------------------------------------
// Webhooks
// ---------------------------------------------------------------------------
async function createWebhook({ merchantId, url, secret, events }) {
const { rows } = await query(
`INSERT INTO webhooks (merchant_id, url, secret, events)
VALUES ($1, $2, $3, $4)
RETURNING id, merchant_id, url, events, is_active, created_at`,
[merchantId, url, secret, events]
);
return rows[0];
}
async function getWebhooksByMerchant(merchantId) {
const { rows } = await query(
`SELECT id, merchant_id, url, events, is_active, created_at, updated_at
FROM webhooks WHERE merchant_id = $1 ORDER BY created_at DESC`,
[merchantId]
);
return rows;
}
async function getWebhookById(id) {
const { rows } = await query(
`SELECT * FROM webhooks WHERE id = $1`,
[id]
);
return rows[0] || null;
}
async function updateWebhook(id, merchantId, { url, events, isActive }) {
const fields = [];
const values = [];
let idx = 1;
if (url !== undefined) { fields.push(`url = $${idx++}`); values.push(url); }
if (events !== undefined) { fields.push(`events = $${idx++}`); values.push(events); }
if (isActive !== undefined) { fields.push(`is_active = $${idx++}`); values.push(isActive); }
if (!fields.length) return getWebhookById(id);
fields.push(`updated_at = NOW()`);
values.push(id, merchantId);
const { rows } = await query(
`UPDATE webhooks SET ${fields.join(', ')}
WHERE id = $${idx++} AND merchant_id = $${idx}
RETURNING id, merchant_id, url, events, is_active, updated_at`,
values
);
return rows[0] || null;
}
async function deleteWebhook(id, merchantId) {
const { rowCount } = await query(
`DELETE FROM webhooks WHERE id = $1 AND merchant_id = $2`,
[id, merchantId]
);
return rowCount > 0;
}
/**
* Returns all active webhooks subscribed to a given event type.
*/
async function getActiveWebhooksForEvent(eventType) {
const { rows } = await query(
`SELECT * FROM webhooks
WHERE is_active = TRUE AND ($1 = ANY(events) OR '*' = ANY(events))`,
[eventType]
);
return rows;
}
// ---------------------------------------------------------------------------
// Deliveries
// ---------------------------------------------------------------------------
async function createDelivery({ webhookId, eventType, payload }) {
const { rows } = await query(
`INSERT INTO webhook_deliveries (webhook_id, event_type, payload)
VALUES ($1, $2, $3)
RETURNING *`,
[webhookId, eventType, JSON.stringify(payload)]
);
return rows[0];
}
async function updateDelivery(id, { status, httpStatus, responseBody, nextRetryAt, deliveredAt, attempt }) {
const { rows } = await query(
`UPDATE webhook_deliveries
SET status = COALESCE($2, status),
http_status = COALESCE($3, http_status),
response_body = COALESCE($4, response_body),
next_retry_at = $5,
delivered_at = $6,
attempt = COALESCE($7, attempt)
WHERE id = $1
RETURNING *`,
[id, status, httpStatus, responseBody, nextRetryAt ?? null, deliveredAt ?? null, attempt]
);
return rows[0];
}
async function getDeliveriesByWebhook(webhookId, { page = 1, limit = 20 } = {}) {
const offset = (page - 1) * limit;
const { rows } = await query(
`SELECT id, event_type, status, http_status, attempt, delivered_at, created_at
FROM webhook_deliveries
WHERE webhook_id = $1
ORDER BY created_at DESC
LIMIT $2 OFFSET $3`,
[webhookId, limit, offset]
);
const { rows: countRows } = await query(
`SELECT COUNT(*) AS total FROM webhook_deliveries WHERE webhook_id = $1`,
[webhookId]
);
return { deliveries: rows, total: parseInt(countRows[0].total) };
}
/**
* Returns failed deliveries whose next_retry_at is due.
*/
async function getDueRetries(maxAttempts = 5) {
const { rows } = await query(
`SELECT d.*, w.url, w.secret
FROM webhook_deliveries d
JOIN webhooks w ON w.id = d.webhook_id
WHERE d.status = 'failed'
AND d.attempt < $1
AND d.next_retry_at <= NOW()
AND w.is_active = TRUE`,
[maxAttempts]
);
return rows;
}
module.exports = {
createWebhook,
getWebhooksByMerchant,
getWebhookById,
updateWebhook,
deleteWebhook,
getActiveWebhooksForEvent,
createDelivery,
updateDelivery,
getDeliveriesByWebhook,
getDueRetries,
};