Repository navigation
Expand file tree
/
Copy pathbasic.ts
More file actions
79 lines (69 loc) · 2.47 KB
/
Copy pathbasic.ts
File metadata and controls
79 lines (69 loc) · 2.47 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
/**
* End-to-end example: a receiver that verifies signatures, and an app that
* sends it a webhook through Hookgres.
*
* docker compose up -d postgres && pnpm build && node examples/basic.ts
*
* Node 22.18+ runs TypeScript files directly. Set DATABASE_URL to use your
* own Postgres.
*/
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { Hookgres, verifyWebhook, type WebhookEnvelope } from "hookgres";
import pg from "pg";
const databaseUrl =
process.env.DATABASE_URL ??
"postgres://postgres:postgres@localhost:5432/postgres";
// --- The receiving side (your customer's server) ---------------------------
let secret = "";
let resolveReceived: (event: WebhookEnvelope) => void;
const received = new Promise<WebhookEnvelope>((resolve) => {
resolveReceived = resolve;
});
const server = createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (chunk: Buffer) => chunks.push(chunk));
req.on("end", () => {
try {
const event = verifyWebhook<WebhookEnvelope>({
secret,
headers: req.headers,
body: Buffer.concat(chunks),
});
res.writeHead(204).end();
resolveReceived(event);
} catch {
res.writeHead(400).end("invalid signature");
}
});
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const { port } = server.address() as AddressInfo;
// --- The sending side (your app) -------------------------------------------
const pool = new pg.Pool({ connectionString: databaseUrl });
const hookgres = new Hookgres({ pool, schema: "hookgres_example" });
await pool.query("DROP SCHEMA IF EXISTS hookgres_example CASCADE"); // a previous run may have crashed
await hookgres.migrate();
hookgres.start();
const endpoint = await hookgres.createEndpoint({
tenantId: "acme",
url: `http://127.0.0.1:${port}/webhooks`,
eventTypes: ["invoice.paid"],
});
secret = endpoint.secret; // in real life, shown once to your customer
const { message } = await hookgres.send({
tenantId: "acme",
eventType: "invoice.paid",
payload: { invoiceId: "in_123", amount: 4200, currency: "eur" },
});
const timeout = setTimeout(() => {
console.error("No webhook received within 10s");
process.exit(1);
}, 10_000);
const event = await received;
clearTimeout(timeout);
console.log(`Received ${event.type} for message ${message.id}:`, event.data);
await hookgres.stop();
await pool.query("DROP SCHEMA hookgres_example CASCADE");
await pool.end();
server.close();