From c80cc49d48b34c89ed827cc21a112435f8f0a66f Mon Sep 17 00:00:00 2001 From: SuperFire <36259493+Sup3rFire@users.noreply.github.com> Date: Wed, 10 Apr 2024 13:06:21 +0700 Subject: [PATCH] refactor: Use theorypack on api --- src/client/Client.ts | 11 ++++------- src/util/api.ts | 43 ++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 44 insertions(+), 10 deletions(-) diff --git a/src/client/Client.ts b/src/client/Client.ts index fcf1726..4ca2359 100644 --- a/src/client/Client.ts +++ b/src/client/Client.ts @@ -64,13 +64,10 @@ export default class Client extends EventEmitter { * A "user" account must not be used and a "bot" account is required. To obtain one, contact [osk](https://osk.sh/). */ public async login_password(username: string, password: string): Promise { - let auth = await api( - "/users/authenticate", - undefined, - { "Content-Type": "application/json" }, - "POST", - { username, password } - ); + let auth = await api("/users/authenticate", undefined, undefined, "POST", { + username, + password, + }); await this.login(auth.token); } diff --git a/src/util/api.ts b/src/util/api.ts index fb4730f..03fb403 100644 --- a/src/util/api.ts +++ b/src/util/api.ts @@ -1,7 +1,41 @@ +import { Packr, Unpackr, addExtension } from "msgpackr"; import { APIResponse } from "./types"; const cache: Map = new Map(); +addExtension({ + type: 1, + read: (e) => + null === e + ? { + success: true, + } + : { + success: true, + ...e, + }, +}); +addExtension({ + type: 2, + read: (e) => + null === e + ? { + success: false, + } + : { + success: false, + error: e, + }, +}); + +const unpackr = new Unpackr({ + bundleStrings: true, +}); + +const packr = new Packr({ + bundleStrings: true, +}); + export default async function ( endpoint: string, token?: string, @@ -24,16 +58,19 @@ export default async function ( } let headers: any = { - Accept: "application/json", + Accept: "application/vnd.osk.theorypack", ...headers_, }; if (token) headers.Authorization = `Bearer ${token}`; + if (method == "POST") headers["content-type"] = "application/vnd.osk.theorypack"; let response: Promise = fetch(`https://tetr.io/api${endpoint}`, { method, - body: body_ ? Buffer.from(JSON.stringify(body_)) : undefined, + body: body_ ? packr.pack(body_) : undefined, headers, - }).then((res) => res.json()); + }) + .then((res) => res.arrayBuffer()) + .then((res) => unpackr.unpack(Buffer.from(res))); if (cache_) cache.set(cache_.key, { expire: cache_.expire, data: response });