Webhooks

You can create webhooks within your environments to listen for specific content management actions.

import express from 'express';

const app = express();

// SecretKey from Brighlever webhook definition
const secretKey='...'; 

const validatePayload=(payload,signature)=>{
    return (signature==crypto.createHmac("sha256", secretKey)
          .update(payload, "utf8")
          .digest("hex"))
}

// Important for Brightlever payloads
app.use(express.json({ type: 'application/*' }));

app.post('/webhook', (req, res) => {
    const payload = req.body;

    if(!validatePayload(payload,req.headers["x-brightlever-signature"])){
         res.sendStatus(500); 
    } else {
      
        console.log(`Webhook received: ${payload.action} event for ID ${payload.data._sys.id}`);
        console.log(`Webhook received: ${payload.sourceId} event source id`);
        // Your custom logic to process the event goes here

        res.sendStatus(200); 
    }  
});

app.listen(3000, () => console.log('Webhook server listening on port 3000'));

If you use webhooks to interact with the Brighlever api it is important to send the "X-Brightlever-Source-ID" header set to the sourceId that is in the webhook payload.

This lets Brightlever know that the webhook handler doesn't need to be renotified about the update.

You can also register the source id with the node client module.

import Client from '@brightlever/client`;
import express from 'express';

const app = express();

// SecretKey from Brighlever webhook definition
const secretKey='...'; 

// API key generated from within the Brightlever environment admin.
const apiKey='...'; 

// Environment ID from Brightlever environment admin.
const environmentId='...'; 

const validatePayload=(payload,signature)=>{
    return (signature==crypto.createHmac("sha256", secretKey)
        .update(payload, "utf8")
        .digest("hex"))
}

// Important for Brightlever payloads
app.use(express.json({ type: 'application/*' }));

app.post('/webhook', async (req, res) => {
    const payload = req.body;

    if(!validatePayload(payload,req.headers["x-brightlever-signature"])){
         res.sendStatus(500); 
    } else {
        if(payload.data?._sys?.contentType=='widget'
            && !payload.data.enrichmentAttribute){
            
            const doc=payload.data;

            const client=new Client({
                environment_id:environmentId,
                access_token:apiKey,
                source_id:payload.sourceId
            });
     
            // Look update custom api to 
            // get enriched data attribute value.
            doc.enrichmentAttribute=await lookUpData();

            await client.with('widget)
                .id(doc.id)
                .save(doc);

            console.log(`Webhook handled.`)

        }

        res.sendStatus(200); 
    }  
});

app.listen(3000, () => console.log('Webhook server listening on port 3000'));