Skip to content

Implement Client-to-Server Schema serialization / deserialization #97

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions src/Room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,19 +116,28 @@ export class Room<State= any> {
return this.onMessageHandlers.on(this.getMessageHandlerKey(type), callback);
}

public send(type: string | number, message?: any): void {
const initialBytes: number[] = [Protocol.ROOM_DATA];
public send<T extends Schema>(type: T);
public send<T = string | number>(type: T, message?: any);
public send<T = any>(type: string | number | Schema, message?: any): void {
const initialBytes: number[] = type instanceof Schema ? [Protocol.ROOM_DATA_SCHEMA] : [Protocol.ROOM_DATA];

if (typeof(type) === "string") {
encode.string(initialBytes, type);
if (type instanceof Schema) {
encode.string(initialBytes, type.constructor.name);

} else if (typeof(type) === "string") {
encode.string(initialBytes, type);
} else {
encode.number(initialBytes, type);
}

let arr: Uint8Array;

if (message !== undefined) {
if (type instanceof Schema) {
const encoded = new Uint8Array(type.encode(true))
arr = new Uint8Array(initialBytes.length + encoded.byteLength);
arr.set(new Uint8Array(initialBytes), 0);
arr.set(new Uint8Array(encoded), initialBytes.length);
} else if (message !== undefined) {
const encoded = msgpack.encode(message);
arr = new Uint8Array(initialBytes.length + encoded.byteLength);
arr.set(new Uint8Array(initialBytes), 0);
Expand Down