Skip to content

Commit

Permalink
feat(client): event proxy (#620)
Browse files Browse the repository at this point in the history
  • Loading branch information
pluvrt authored May 22, 2024
1 parent 99b5ca9 commit df1342c
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 4 deletions.
32 changes: 32 additions & 0 deletions .changeset/smooth-kings-swim.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
"@pluv/client": patch
---

Added event proxy as a new way to invoke event procedures.

```ts
// backend

const router = io.router({
SEND_MESSAGE: io.procedure
.input(z.object({ message: z.string() }))
.broadcast(({ message }) => ({ RECEIVE_MESSAGE: { message } })),
});

// frontend
const client = createClient(/* ... */);

// Both of the examples below are equivalent.

client.event("RECEIVE_MESSAGE", ({ data }) => {
const { message } = data;

console.log(message);
});

client.event.RECEIVE_MESSAGE(({ data }) => {
const { message } = data;

console.log(message);
});
```
20 changes: 17 additions & 3 deletions packages/client/src/PluvRoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,11 +319,25 @@ export class PluvRoom<
this._stateNotifier.subjects["my-presence"].next(null);
}

public event = <TEvent extends keyof InferIOOutput<TIO>>(
public event = new Proxy(
<TEvent extends keyof InferIOOutput<TIO>>(
event: TEvent,
callback: EventNotifierSubscriptionCallback<TIO, TEvent>,
): (() => void) => {
return this._eventNotifier.subscribe(event, callback);
},
{
get(fn, prop) {
return (callback: EventNotifierSubscriptionCallback<TIO, any>): (() => void) => {
return fn(prop, callback);
};
},
},
) as (<TEvent extends keyof InferIOOutput<TIO>>(
event: TEvent,
callback: EventNotifierSubscriptionCallback<TIO, TEvent>,
): (() => void) => {
return this._eventNotifier.subscribe(event, callback);
) => () => void) & {
[event in keyof InferIOOutput<TIO>]: (callback: EventNotifierSubscriptionCallback<TIO, event>) => () => void;
};

public getConnection(): WebSocketConnection {
Expand Down
1 change: 0 additions & 1 deletion tests/e2e/src/server/yjs/node/pluv-io.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { createIO } from "@pluv/io";
import { platformNode } from "@pluv/platform-node";
import { z } from "zod";
import { prisma } from "../../../prisma";
import { InferIOOutput } from "@pluv/types";

const PLUV_AUTH_SECRET = "secret123";

Expand Down

0 comments on commit df1342c

Please sign in to comment.