A set of useful helper methods for writing functions to handle Cloudflare Pub/Sub messages (https://developers.cloudflare.com/pub-sub/)

Overview

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>> {

    // Messages may be batched at higher throughputs, so we should loop over
    // the incoming messages and process them as needed.
    let messagesToKeep: Array<PubSubMessage>
    for (let msg of messages) {
        console.log(msg);
        // Drop debug messages sent by our clients to reduce the load on our
        // subscribers.
        if (!msg.topic.startsWith("debug") {
            messagesToKeep.push(msg)
        }
    }

    return messagesToKeep;
}

const worker = {
    async fetch(req: Request, env: any, ctx: ExecutionContext) {
        // Critical: you must validate the incoming request is from your Broker
        // In the future, Workers will be able to do this on your behalf for Workers
        // in the same account as your Pub/Sub Broker.
        if (await isValidBrokerRequest(req)) {
            // Parse the PubSub message
            let incomingMessages: Array<PubSubMessage> = await req.json();

            // Pass the messages to our pubsub handler, and capture the returned
            // message.
            let outgoingMessages = await pubsub(incomingMessages, env, ctx);

            // Re-serialize the messages and return a HTTP 200.
            // The Content-Type is optional, but must either by
            // "application/octet-stream" or left empty.
            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.

You might also like...

The invoker based on event model provides an elegant way to call your methods in another container via promisify functions

The invoker based on event model provides an elegant way to call your methods in another container via promisify functions. (like child-processes, iframe, web worker etc).

Dec 29, 2022

A collection of functions and methods to make it easier for you to create applications.

def-helper A collection of functions and methods to make it easier for you to create applications. Install npm install --save def-helper Usage import

Oct 13, 2022

AdsPower supports Local API, which has functions like reading and writing account configuration information, opening and closing browsers, searching for accounts.

AdsPower supports Local API, which has functions like reading and writing account configuration information, opening and closing browsers, searching for accounts. Besides, it can cooperate with Selenium and Puppeteer to execute browser operations automatically.

Dec 1, 2022

A JavaScript Library for things I use often, as well as some helper functions

Elements A JavaScript Library for things I use often, as well as some helper functions. Full documentation below. Inspired by Habitat, another library

Apr 21, 2022

Babel plugin and helper functions for interoperation between Node.js native ESM and Babel ESM

babel-plugin-node-cjs-interop and node-cjs-interop: fix the default import interoperability issue in Node.js The problem to solve Consider the followi

Nov 6, 2022

A chat logs online saver for discord bots to save messages history & cleared messages online

A chat logs online saver for discord bots to save messages history & cleared messages online

Chat Logs NPM package that saves messages online to view it later Useful for bots where users can save messages history & cleared messages online Supp

Dec 28, 2022

The Remix version of the fakebooks app demonstrated on https://remix.run. Check out the CRA version: https://github.com/kentcdodds/fakebooks-cra

Remix Fakebooks App This is a (very) simple implementation of the fakebooks mock app demonstrated on remix.run. There is no database, but there is an

Dec 22, 2022

nest연습용 (w. https://github.com/seuiggi, https://github.com/okysky1121)

A progressive Node.js framework for building efficient and scalable server-side applications. Description Nest framework TypeScript starter repository

Oct 5, 2022

GraphErr is an open-source error handling library for GraphQL implementations in Deno. It's a lightweight solution that provides developers with descriptive error messages, reducing ambiguity and improving debugging.

GraphErr is an open-source error handling library for GraphQL implementations in Deno. It's a lightweight solution that provides developers with descriptive error messages, reducing ambiguity and improving debugging.

GraphErr Descriptive GraphQL error handling for Deno/Oak servers. Features Provides additional context to GraphQL's native error messaging for faster

Nov 1, 2022
Comments
  • test source code directly

    test source code directly

    This line:

    https://github.com/cloudflare/pubsub/blob/037070f3ea8cf116043280aa6c4c01772f492722/tests/valid.ts#L6

    Should be:

    import { isValidBrokerRequest } from "../src";
    

    This is so that you can always run npm test without needing to rebuild the project first.

    This is necessary as of https://github.com/cloudflare/pubsub/commit/037070f3ea8cf116043280aa6c4c01772f492722#diff-7ae45ad102eab3b6d7e7896acd08c427a9b25b346470d7bc6507b6481575d519L18 since the pretest tsc step was removed.. so right now tests are always testing outdated code unless you're doing npm run build && npm test repeatedly.

    opened by lukeed 0
An interceptor to validate and decode Pub/Sub push messages for endpoints

NestJS GCP Pub/Sub Interceptor Provides an Interceptor for NestJS to automagically validate and unwrap HTTP push messages from Google Cloud Platform's

Hiphops 3 Dec 15, 2022
ish.ninja is a free online platform to allocate a unique ish.ninja sub handle name for a BlueSky account.

ish.ninja ish.ninja is a free online platform to allocate a unique ish.ninja sub handle name for a BlueSky account. It is built using Next.js, Xata, T

Ishaan Bedi 6 May 9, 2023
A small (~600B gzip), useful set of methods for lazy iteration of iterables.

@ricokahler/lazy · A small (~600B gzip*), useful set of methods for lazy iteration of iterables. Why this lazy lib? Do I even need a lazy lib? Install

Rico Kahler 11 Sep 10, 2022
Helper package to handle requests to a jschan api instance.

jschan-api-sdk Helper package to handle requests to a jschan api instance. How to use npm install ussaohelcim/jschan-api-sdk const { jschan } = requir

Michell 3 Jun 30, 2022
Software for the next generation of social media. https://gitlab.com/soapbox-pub/soapbox-fe

Soapbox FE Soapbox FE is a frontend for Mastodon and Pleroma with a focus on custom branding and ease of use. It's part of the Soapbox project. Try it

Soapbox 52 Dec 30, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Um bot de suporte feito usando threads para o Discord, 100% customizável, feito em JavaScript e inspirado no Rio Helper do servidor Elixir Lab e na Loritta Helper do serivdor de suporte da Loritta.

Ticket Bot Um bot de suporte feito usando threads para o Discord, 100% customizável, feito em JavaScript e inspirado no Rio Helper do servidor Elixir

ADG 6 Dec 21, 2022
Provides simple and the most useful methods to string operations in JavaScript / Node.js

?? Strops (String Operations) Provides simple methods for the most useful operations with substrings: - remove, replace, get from A to B, get from A t

Max Shane 3 May 20, 2022