-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebhooks-db.js
91 lines (83 loc) · 2.77 KB
/
webhooks-db.js
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
/**
* WebhooksDB to track webhook information for users.
*/
const sqlite3 = require('sqlite3');
const db = new sqlite3.Database('webhooks.db');
db.run(`CREATE TABLE IF NOT EXISTS webhooks (
username TEXT PRIMARY KEY,
last_webhook_date TEXT,
wait_start_date TEXT,
wait_end_date TEXT
)`);
/**
* Update webhook information for a user
* @param {string} username - The user's identifier
* @param {Object} data - Object containing webhook data
* @param {string} [data.lastWebhookDate] - ISO8601 formatted date string of the last received webhook
* @param {string} [data.waitStartDate] - ISO8601 formatted date string for when to start waiting
* @param {string} [data.waitEndDate] - ISO8601 formatted date string for when to stop waiting
*/
function updateWebhookInfo(username, data) {
const { lastWebhookDate, waitStartDate, waitEndDate } = data;
db.run(`INSERT OR REPLACE INTO webhooks
(username, last_webhook_date, wait_start_date, wait_end_date)
VALUES (?,
COALESCE(?, (SELECT last_webhook_date FROM webhooks WHERE username = ?)),
COALESCE(?, (SELECT wait_start_date FROM webhooks WHERE username = ?)),
COALESCE(?, (SELECT wait_end_date FROM webhooks WHERE username = ?))
)`,
username,
lastWebhookDate, username,
waitStartDate, username,
waitEndDate, username
);
}
/**
* Get webhook information for a user
* @param {string} username - The user's identifier
* @param {function} callback - Callback function(err, webhookInfo)
*/
function getWebhookInfo(username, callback) {
db.get('SELECT * FROM webhooks WHERE username = ?',
[username],
(err, row) => {
if (err) {
callback(err, null);
} else {
callback(null, row || {});
}
}
);
}
/**
* Check if a user is waiting for a webhook
* @param {string} username - The user's identifier
* @param {function} callback - Callback function(err, isWaiting)
*
function isWaitingForWebhook(username, callback) {
const now = new Date().toISOString();
db.get('SELECT * FROM webhooks WHERE username = ? AND wait_start_date <= ? AND wait_end_date > ?',
[username, now, now],
(err, row) => {
if (err) {
callback(err, false);
} else {
callback(null, !!row);
}
}
);
}
*/
/**
* Clean up expired webhook waits
*/
function cleanupExpiredWaits() {
const now = new Date().toISOString();
db.run('UPDATE webhooks SET wait_start_date = NULL, wait_end_date = NULL WHERE wait_end_date <= ?', now);
}
// Run cleanup periodically (e.g., every hour)
setInterval(cleanupExpiredWaits, 60 * 60 * 1000);
module.exports = {
updateWebhookInfo,
getWebhookInfo
};