Skip to content
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

default error handler #20

Merged
merged 1 commit into from
Jan 21, 2024
Merged
Show file tree
Hide file tree
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
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,11 @@ const amo = new Amo("mydomain.amocrm.ru", auth_object, options_object);

- `request_delay: number` (ms) - amo backend limits you to _7 reqs/sec_, so the client manages with it by performing
requests sequentially with delay (_150ms_ by default). You could set your own delay number (or zero, if you want).
- `on_token: (new_token: OAuth) => void | Promise<void>` - callback, that will be called on _new token_ event (during
- `on_token?: (new_token: OAuth) => void | Promise<void>` - callback, that will be called on _new token_ event (during
receiving from a code or refreshing). Lib manages the auth/token stuff for you, but it is strongly recommended to
store the new token persistently somewhere you want (fs, db) to provide it on the next app start.
- `on_error?: (error: Error) => void | Promise<void>;` - default error handler. If provided, it will be called instead
of throwing errors. Request lifycycle will not be interrupted and you receive `null` as a response.

---

Expand Down Expand Up @@ -295,6 +297,18 @@ try {
}
```

Also you could use default non-intercepted error handler passed with the `options` to client constructor:

```ts
const amo = new Amo("mydomain.amocrm.ru", auth_object, {
on_error: (err) => console.error("Amo emits error", err);
});
const lead = amo.lead.getLeadById(6969);
if (lead) {
// do logic
}
```

# Contribution

Pull request, issues and feedback are very welcome. Code style is formatted with deno fmt.
Expand Down
65 changes: 35 additions & 30 deletions src/core/rest-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,18 @@ export class RestClient {
}

private async authorization(value: OAuthCode | OAuthRefresh): Promise<void> {
try {
const res = await this.queue.push(fetch, `${this.url_base}/oauth2/access_token`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(value),
});
if (res.ok === false) {
throw new AuthError(res.body ? await res.json() : "Empty");
}
const data = (await res.json()) as OAuth;
this._token = { ...data, expires_at: Date.now() + (data.expires_in * 1000) };
if (this.options?.on_token !== undefined) {
this.options.on_token(this._token);
}
} catch (err) {
throw err;
const res = await this.queue.push(fetch, `${this.url_base}/oauth2/access_token`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(value),
});
if (res.ok === false) {
throw new AuthError(res.body ? await res.json() : "Empty");
}
const data = (await res.json()) as OAuth;
this._token = { ...data, expires_at: Date.now() + (data.expires_in * 1000) };
if (this.options?.on_token !== undefined) {
this.options.on_token(this._token);
}
}

Expand Down Expand Up @@ -80,21 +76,30 @@ export class RestClient {
}

async request<T>(method: HttpMethod, init: RequestInit): Promise<T> {
await this.checkToken();
const target = `${init.url_base ?? this.url_base}${init?.url}${init.query ? "?" + init.query : ""}`;

const res = await this.queue.push(fetch, target, {
method: method,
headers: {
"Authorization": `${this._token?.token_type} ${this._token?.access_token}`,
"Content-Type": "application/json",
...init.headers,
},
body: init.payload ? JSON.stringify(init.payload) : undefined,
});
try {
await this.checkToken();
const target = `${init.url_base ?? this.url_base}${init?.url}${init.query ? "?" + init.query : ""}`;

const res = await this.queue.push(fetch, target, {
method: method,
headers: {
"Authorization": `${this._token?.token_type} ${this._token?.access_token}`,
"Content-Type": "application/json",
...init.headers,
},
body: init.payload ? JSON.stringify(init.payload) : undefined,
});

await this.checkError(res, method);
return res.body ? (await res.json()) as T : null as T;
await this.checkError(res, method);
return res.body ? (await res.json()) as T : null as T;
} catch (err) {
if (this.options?.on_error) {
this.options.on_error(err);
return null as T;
} else {
throw err;
}
}
}

get<T>(init: RequestInit): Promise<T> {
Expand Down
6 changes: 6 additions & 0 deletions src/typings/lib.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { AuthError } from "../errors/auth.ts";
import { NoContentError } from "../errors/no-content.ts";
import { HttpError } from "../errors/http.ts";
import { WebhookError } from "../errors/webhook.ts";
import { ApiError } from "../errors/api.ts";
import { OAuth } from "./auth.ts";
import { JSONValue } from "./utility.ts";

export type Options = {
request_delay?: number;
on_token?: (token: OAuth) => void | Promise<void>;
on_error?: (error: Error | AuthError | ApiError | NoContentError | HttpError | WebhookError) => void | Promise<void>;
};

export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
Expand Down
15 changes: 15 additions & 0 deletions tests/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,18 @@ Deno.test("should return AuthError", async () => {

await sleep(200);
});

Deno.test("should return AuthError to error handler", async () => {
mf.mock("POST@/oauth2/access_token", () => {
return new Response(null, { status: 403 });
});

const amo = new Amo("mydomain.amocrm.ru", { ...auth, ...token, expires_at: 0 }, {
on_token: (new_token) => console.log("New token obtained", new_token),
on_error: (err) => assertInstanceOf(err, AuthError),
});

await amo.lead.getLeadById(69);

await sleep(200);
});