Pacote JavaScript
Aprenda como usar o pacote JavaScript do cside para webhooks.
Instalando o Pacote
Primeiro, instale nosso pacote de webhooks usando o seguinte comando:
npm i @cside.dev/webhooks
Usando o Pacote
import { constructEvent } from "@cside.dev/webhooks";
const rawBody = req.rawBody; // Este é o corpo bruto da requisição, como você obtém isso dependerá do seu framework HTTP
const signature = req.headers["x-cside-signature"]; // Isso sempre será fornecido nos cabeçalhos.
const event = await constructEvent({
rawBody,
signature,
secret: process.env.CSIDE_WEBHOOK_SECRET, // Este é o secret do webhook que você recebeu ao criar o endpoint de webhook
});
switch (event.type) {
case "alert.created": {
const alert = event.data;
// ^ com tipagem completa
console.log({
type: alert.type,
domain: alert.domain,
target: alert.target,
action: alert.action,
});
}
}
Exemplos
import Fastify from 'fastify';
import { constructEvent } from "@cside.dev/webhooks";
const fastify = Fastify({ logger: true });
await fastify.register(import('@fastify/raw-body'), {
field: 'rawBody',
global: false,
routes: ['/webhook']
});
fastify.post('/webhook', {
config: { rawBody: true }
}, async (request, reply) => {
const signature = request.headers['x-cside-signature'];
const webhookEvent = await constructEvent(
request.rawBody,
signature,
process.env.CSIDE_WEBHOOK_SECRET!,
);
switch (webhookEvent.event) {
case "alert.created": {
const alert = webhookEvent.data;
console.log({
type: alert.type,
domain: alert.domain,
target: alert.target,
action: alert.action,
});
}
}
});import { createKaitoHandler, KaitoError } from "@kaito-http/core";
import { constructEvent } from "@cside.dev/webhooks";
const app = router()
.get("/", async ({ ctx }) => {
return {
uptime: ctx.uptime,
time_now: Date.now(),
};
})
.post("/", async ({ ctx }) => {
const signature = ctx.req.headers.get("x-cside-signature");
if (!signature) {
throw new KaitoError(400, "Missing signature");
}
const rawBody = await ctx.req.text();
const webhookEvent = await constructEvent(
rawBody,
signature,
process.env.CSIDE_WEBHOOK_SECRET!,
);
switch (webhookEvent.event) {
case "alert.created": {
const alert = webhookEvent.data;
console.log({
type: alert.type,
domain: alert.domain,
target: alert.target,
action: alert.action,
});
}
}
return {
message: "OK!",
};
});