Skip to content

Events

Any Membrane program can emit events on their nodes and subscribe to events on nodes of other programs. In the Schema section we gave the example of a closed on a PullRequest node type.

As another example, let’s say you have a program that handles webhooks. A node in your program could emit a webhookReceived event, and another program could subscribe to that event.

Emitting events

Here we are emitting that webhookReceived event from a program’s root node.

import type {
const root: Root

A gref to the root of this program.

root
} from "membrane"
export function
function endpoint(req: any): void
endpoint
(
req: any
req
) {
switch (`${
req: any
req
.
any
method
} ${
req: any
req
.
any
path
}`) {
case "POST /webhook-path":
const root: Root

A gref to the root of this program.

root
.
any
webhookReceived
.
any
$emit
()
}
}

Reference our event API docs for more on .$emit().

Subscribing to events

Programs can subscribe an action to handle an event. When an event is emitted, the action will be invoked with an additional parameter called event.

Here we are subscribing a program to the webhookReceived event with a doSomething action as its handler. Note that this subscribing program would have the emitting program as a connection.

import type {
import nodes
nodes
} from "membrane"
export async function
function doSomething(_: any, { event }: {
event: any;
}): Promise<void>
doSomething
(
_: any
_
, {
event: any
event
}) {
// Do something with the webhookReceived event
}
export async function
function configure(): Promise<void>
configure
() {
import nodes
nodes
.
any
webhookReceived
.
any
$subscribe
(
function doSomething(_: any, { event }: {
event: any;
}): Promise<void>
doSomething
)
}

Reference our event API docs for more on .$subscribe().