npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

typed-payload

v1.0.1

Published

Library to provide strong typing for any form of event based payload.

Downloads

6

Readme

typed-payload

npm Library to provide strong typing for any form of event based payload.

Motivation

In asynchronous programming, a common design pattern is to have a broker which passes messages from the producer to the consumer, which can be in the same process or in completely different machines. In a simple implementation, this message-passing goes through a multi-purpose channel (Even in complex implementations, it is often still a multi-purpose channel at the low-level view). It is common to create data types such as { event: <event>, payload: <actual message> } to use the same channel for different events. However, due to the channel being multi-purpose, it handles different events and hence difficult to manage typing information of the payload. Discriminated union is the first class way to achieve easy typing but it has its limitations as well.

One common example is in the case of WebSockets. The following code is typical (ignoring serialization):

Common interface:
interface Payload1 {
  var1: string;
}
interface Message1 {
  event: "event 1";
  payload: Payload1;
}

interface Payload2 {
  var2: string;
}
interface Message2 {
  event: "event 2";
  payload: Payload2;
}

type Message = Message1 | Message2;
Producer
const payload1: Payload1 = {
  var1: "value",
};
ws.send({
  event: "event 1",
  payload: payload1,
}: Message1);

...
Consumer:
ws.on("message", (data: Message) => {
  if (data.event === "event 1") {
    // data is of type Message1
  }
  if (data.event === "event 2") {
    // data is of type Message2
  }

  ...
})

This is still manageable using discriminated unions. However, as the number of events grow, this code is not manageable and some would also want to make use of observer pattern so as to keep things more modular. The subscibed function for that event would then need to do a discriminated check.

Consumer:
function subscribeToEvent(event: string, fn: (data: Message) => void) {
  eventSubscribers[event].push(fn);
}

ws.on("message", (data: Message) => {
  eventSubscribers[data.event].forEach(fn => fn(data));
});

// Usage anywhere else in the project
subscribeToEvent("event 1", data => {
  if (data.event === "event 1") { // redundant but necessary
    // data is of type Message1
  }
});

Even with discriminated union, some of the code can still be quite verbose just to comply with type safety.

Solution with typed-payload

Common interface
interface Payload1 {
  var1: string
}
const event1 = TypedPayloadFactory.define<Payload1>("event 1")

interface Payload2 {
  var2: string
}
const event2 = TypedPayloadFactory.define<Payload2>("event 2")
Producer
const payload1: Payload1 = {
  var1: "value",
};
ws.send(event1.create(payload1));

...
Consumer:
ws.on("message", (data) => {
  if (event1.check(data)) {
    // data.payload is now of type Payload1
  }
  if (event2.check(data)) {
    // data.payload is now of type Payload2
  }

  ...
})

There is a slight reduction in verbosity and also better compile time check to reduce human errors. However, where this library shines is by providing much better type safety over discriminated union in observer pattern.

Consumer:
function subscribeToEvent<T>(eventDef: PayloadTypeDef<T>, fn: (payload: T) => void) {
  eventSubscribers[event].push(fn);
}

ws.on("message", (data: Message) => {
  eventSubscribers[data.event].forEach(fn => fn(data.payload));
});

// Usage anywhere else in the project
subscribeToEvent(event1, payload => { // notice we can directly deal with Payload instead of Message
  // payload is of type Payload1
});

Other usages

Payload type guards

Ensures that the payload is indeed of the correct type using your own type guard definition when checking. This parameter would usually be useful only in dev or when debugging. If you rely on this type guard for production code to work, I would suggest refactoring the message-passing protocol.

interface Payload1 {
  var1: string;
}
function isPayload1(obj: any): obj is Payload1 {
  return obj.var1 !== undefined;
}
const event1 = TypedPayloadFactory.define<Payload1>("event 1", isPayload1);

const data = {
  event: "event 1",
  payload: {
    wrongVar1: "value",
  },
}
if (event1.check(data)) { // false
  // not executed
}

Typed payload without payload

Yes you read it right. In some cases, we wish to pass events without payload. Although this library provides little value-add for such use cases, the ability to create typed payload without payload can help with a consistent coding style.

const event1 = TypedPayloadFactory.defineNoPayload("event 1");

const message = event1.create();

if (event1.check(message)) {
  // do something without payload
}