forked from KCEE0901/trustchain-escrow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhookWorker.js
More file actions
57 lines (50 loc) · 1.42 KB
/
Copy pathwebhookWorker.js
File metadata and controls
57 lines (50 loc) · 1.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
import { Worker } from 'bullmq';
import prisma from '../lib/prisma.js';
import { connection } from '../queues/index.js';
export async function processWebhookJob(job) {
const { url, payload, headers = {}, deliveryId } = job.data;
const attempts = job.attemptsMade + 1;
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...headers,
},
body: JSON.stringify(payload),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Webhook failed: ${response.status} ${errorText}`);
}
await prisma.webhookDelivery.update({
where: { id: deliveryId },
data: {
status: 'success',
responseCode: response.status,
attempts,
lastAttemptAt: new Date(),
},
});
console.log(`[WebhookWorker] Delivered to ${url}: ${response.status}`);
} catch (err) {
const isTerminal = attempts >= (job.opts.attempts ?? 1);
await prisma.webhookDelivery.update({
where: { id: deliveryId },
data: {
status: isTerminal ? 'failed' : 'pending',
errorMessage: err.message,
attempts,
lastAttemptAt: new Date(),
},
});
throw err;
}
}
const webhookWorker =
process.env.NODE_ENV === 'test'
? null
: new Worker('webhook', processWebhookJob, {
connection,
});
export default webhookWorker;