Skip to content

Commit

Permalink
Merge pull request #39 from NetsBlox/call-api-wrapper
Browse files Browse the repository at this point in the history
Add callApi wrapper to client to avoid unnecessary code dupe
  • Loading branch information
brollb committed Feb 23, 2024
2 parents 371ce4a + 4185cfe commit f41f55f
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ConnectionRefusedError, RequestError } from "./error";
import NetsBloxApi from './api';
import NetsBloxApi from "./api";

const defaultLocalizer = (text: string) => text;
const isNodeJs = typeof window === "undefined";
Expand Down Expand Up @@ -466,6 +466,20 @@ export default class Cloud {
return await this.fetch(url, opts);
}

/**
* RAII-style API usage where the error handler is called on exception.
*/
async callApi<T>(
fn: (api: NetsBloxApi) => Promise<T>,
): Promise<T | undefined> {
try {
return await fn(this.api);
} catch (err) {
this.onerror(err);
throw err;
}
}

async fetch(url, opts?: RequestInit) {
opts = opts || {};
url = this.url + url;
Expand Down

0 comments on commit f41f55f

Please sign in to comment.