Skip to content

Commit

Permalink
feat(ts): add connection defense
Browse files Browse the repository at this point in the history
  • Loading branch information
fu050409 committed May 18, 2024
1 parent d4dfcf6 commit a3d19c7
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions guest-js/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class Response implements ResponseData {
}

class Client {
connected: boolean = false;
closed: boolean = false;

constructor(public uuid: string | null, public entrance: string) {
Expand All @@ -48,21 +49,28 @@ class Client {
}

async connect(entrance: string | null = null): Promise<void> {
if (this.connected) throw new Error("Client is already connected");
if (this.closed) throw new Error("Client is already closed");
if (!entrance && !this.entrance) {
throw new Error("An oblivion entrance is required");
}
const result: ClientInstance = await invoke("plugin:oblivion|connect", {
entrance: entrance || this.entrance,
});
this.uuid = result.uuid;
this.connected = true;
}

async close(): Promise<void> {
if (!this.connected) throw new Error("Client is not connected");
if (this.closed) throw new Error("Client is already closed");
await invoke("plugin:oblivion|close", { uuid: this.uuid });
this.closed = true;
}

async send_json(data: any): Promise<boolean> {
if (!this.connected) throw new Error("Client is not connected");
if (this.closed) throw new Error("Client is already closed");
const result: boolean = await invoke("plugin:oblivion|send_json", {
uuid: this.uuid,
data,
Expand All @@ -71,6 +79,8 @@ class Client {
}

async recv(): Promise<Response> {
if (!this.connected) throw new Error("Client is not connected");
if (this.closed) throw new Error("Client is already closed");
const result: ResponseData = await invoke("plugin:oblivion|recv", {
uuid: this.uuid,
});
Expand Down

0 comments on commit a3d19c7

Please sign in to comment.