Skip to content

Commit

Permalink
refactor: Use theorypack on api
Browse files Browse the repository at this point in the history
  • Loading branch information
Sup3rFire committed Apr 10, 2024
1 parent dbacb97 commit c80cc49
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 10 deletions.
11 changes: 4 additions & 7 deletions src/client/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
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);
}
Expand Down
43 changes: 40 additions & 3 deletions src/util/api.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,41 @@
import { Packr, Unpackr, addExtension } from "msgpackr";
import { APIResponse } from "./types";

const cache: Map<string, { expire: number; data: any }> = 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,
Expand All @@ -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<APIResponse> = 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 });

Expand Down

0 comments on commit c80cc49

Please sign in to comment.