Here's an example in Javascript for Cloudflare's serverless Workers platform.
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Respond to the request
* @param {Request} request
*/
async function handleRequest(request) {
// check we have a POST request
if (request.method !== "POST") {
return new Response(
"Only POST requests are handled.",
{status: 200}
)
}
try {
// receive input
const data = await request.json()
// get title and feed name
const item_title = data.title
const feed_name = data.feed.name
// process
// Store in KV store (Key-Value store)
await FEEDCONTROL.put('last_title', item_title)
await FEEDCONTROL.put('data', JSON.stringify(data))
return new Response(
`New item from ${feed_name}: ${item_title}`,
{status: 200}
)
} catch (e) {
return new Response(`Error: ${e}`, {status: 200})
}
}
event.respondWith(handleRequest(event.request))
})
/**
* Respond to the request
* @param {Request} request
*/
async function handleRequest(request) {
// check we have a POST request
if (request.method !== "POST") {
return new Response(
"Only POST requests are handled.",
{status: 200}
)
}
try {
// receive input
const data = await request.json()
// get title and feed name
const item_title = data.title
const feed_name = data.feed.name
// process
// Store in KV store (Key-Value store)
await FEEDCONTROL.put('last_title', item_title)
await FEEDCONTROL.put('data', JSON.stringify(data))
return new Response(
`New item from ${feed_name}: ${item_title}`,
{status: 200}
)
} catch (e) {
return new Response(`Error: ${e}`, {status: 200})
}
}
This example uses the Workers KV store to store the last webhook data received with the key 'data', as well as the item title with key 'last_title'. You don't need to use the KV store when receiving webhooks, but it's one easy way to test if the script is working as it should.
To run this example you will need to do the following:
- Set up a KV namespace
- Bind the namespace to a variable (we've used FEEDCONTROL in the example script)
- You're ready to go. To check if everything worked okay, you can examine your KV store to see if the data and last_title entries appear.
Comments
0 comments
Please sign in to leave a comment.