pubsub
A set of useful helper methods for writing functions to handle Cloudflare Pub/Sub messages. This includes:
- A
isValidBrokerRequest
helper for authenticating incoming on-publish webhooks
- A
PubSubMessage
type with the fields sent from the Broker to your Worker for use with TypeScript-based Workers and/or for type-aware editors.
Installation
Use npm
to install:
npm install @cloudflare/pubsub
Example
The following example shows how to use isValidBrokerRequest
in a Worker to validate incoming on-publish webhooks from a Pub/Sub broker.
You can use wrangler
to bundle your code for deployment to Cloudflare Workers.
import { isValidBrokerRequest, PubSubMessage } from "@cloudflare/pubsub"
async function pubsub(
messages: Array<PubSubMessage>,
env: any,
ctx: ExecutionContext
): Promise<Array<PubSubMessage>> {
let messagesToKeep: Array<PubSubMessage>
for (let msg of messages) {
console.log(msg);
if (!msg.topic.startsWith("debug") {
messagesToKeep.push(msg)
}
}
return messagesToKeep;
}
const worker = {
async fetch(req: Request, env: any, ctx: ExecutionContext) {
if (await isValidBrokerRequest(req)) {
let incomingMessages: Array<PubSubMessage> = await req.json();
let outgoingMessages = await pubsub(incomingMessages, env, ctx);
return new Response(JSON.stringify(outgoingMessages), { status: 200 });
}
return new Response("not a valid Broker request", { status: 403 });
},
};
export default worker;
You can use wranger publish
to publish this directly: the latest wrangler
supports TypeScript natively.
License
BSD 3-Clause licensed. Copyright Cloudflare, Inc. 2022.