|
| 1 | +import { Webhook, WebhookRequest } from "@userhub/sdk/webhook"; |
| 2 | +import { createServer } from "http"; |
| 3 | + |
| 4 | +async function main() { |
| 5 | + const port = process.env.PORT || "8000"; |
| 6 | + |
| 7 | + const signingSecret = process.env.SIGNING_SECRET; |
| 8 | + if (!signingSecret) { |
| 9 | + console.error("SIGNING_SECRET required"); |
| 10 | + process.exit(1); |
| 11 | + } |
| 12 | + |
| 13 | + const webhook = new Webhook(signingSecret); |
| 14 | + |
| 15 | + webhook.onEvent((event) => { |
| 16 | + console.log("Event:", event.type); |
| 17 | + |
| 18 | + if (event.type === "organizations.changed") { |
| 19 | + const organization = event.organizationsChanged.organization; |
| 20 | + console.log( |
| 21 | + " - Organization:", |
| 22 | + organization.id, |
| 23 | + organization.displayName, |
| 24 | + ); |
| 25 | + } else if (event.type === "users.changed") { |
| 26 | + const user = event.usersChanged.user; |
| 27 | + console.log(" - User:", user.id, user.displayName); |
| 28 | + } |
| 29 | + }); |
| 30 | + |
| 31 | + const server = createServer((req, res) => { |
| 32 | + const chunks = []; |
| 33 | + |
| 34 | + req.on("data", (v) => { |
| 35 | + chunks.push(v); |
| 36 | + }); |
| 37 | + |
| 38 | + req.on("end", async () => { |
| 39 | + const r = await webhook.handle( |
| 40 | + new WebhookRequest({ |
| 41 | + body: chunks.join(""), |
| 42 | + headers: req.headers, |
| 43 | + }), |
| 44 | + ); |
| 45 | + |
| 46 | + res.statusCode = r.statusCode; |
| 47 | + for (const [name, value] of r.headers.entries()) { |
| 48 | + res.setHeader(name, value); |
| 49 | + } |
| 50 | + res.end(r.body); |
| 51 | + }); |
| 52 | + }); |
| 53 | + |
| 54 | + server.listen(port, () => { |
| 55 | + console.log(`Listening on ${port}`); |
| 56 | + }); |
| 57 | +} |
| 58 | + |
| 59 | +main().catch(console.error); |
0 commit comments