Skip to content

Commit

Permalink
refactor: throw useful error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
DTrombett committed May 11, 2023
1 parent a21609a commit 0c73a4e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
4 changes: 2 additions & 2 deletions src/structures/Base.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { inspect } from "node:util";
import type { Client, Jsonify, ObjectJson } from "..";

const identifierName = "class name";
const identifierName = "Class name!";

/**
* Rappresenta una struttura base
Expand Down Expand Up @@ -59,7 +59,7 @@ export class Base<T extends ObjectJson = ObjectJson> {
}

protected isJson<O extends ObjectJson>(data: O | T): data is O {
return data[identifierName] === this.constructor.name;
return typeof data[identifierName] !== "undefined";
}

protected handleJson(data: Jsonify<Base>) {
Expand Down
27 changes: 20 additions & 7 deletions src/util/apiRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@ import { formatDate } from "..";
export const apiRequest = async <T extends Json, R extends boolean = false>(
path: string,
client: Client,
options?: Partial<{
options: Partial<{
body: Json;
method: HttpMethod;
noWaitAfter: R;
}>
}> = {}
) => {
options.method ??= "GET";
const res = await request(
`https://www.portaleargo.it/appfamiglia/api/rest/${path}`,
{
Expand All @@ -32,20 +33,32 @@ export const apiRequest = async <T extends Json, R extends boolean = false>(
client.token?.expireDate && formatDate(client.token.expireDate),
...client.headers,
},
method: options?.method,
method: options.method,
body:
options?.method === "POST" ? JSON.stringify(options.body) : undefined,
options.method === "POST" ? JSON.stringify(options.body) : undefined,
}
);
if (client.debug)
console.log(`${options?.method ?? "GET"} /${path} ${res.statusCode}`);
if (client.debug) console.log(`${options.method} /${path} ${res.statusCode}`);
const result = {
res,
} as {
res: typeof res;
body: R extends true ? undefined : T;
};

if (options?.noWaitAfter !== true) result.body = await res.body.json();
if (options.noWaitAfter !== true) {
const text = await res.body.text();

try {
result.body = JSON.parse(text);
} catch (err) {
throw new TypeError(
`${options.method} /${path} failed with status code ${res.statusCode}`,
{
cause: text,
}
);
}
}
return result;
};

0 comments on commit 0c73a4e

Please sign in to comment.