From d785f0b643015d19f88158183ff74fcf40f79931 Mon Sep 17 00:00:00 2001 From: Brian Broll Date: Thu, 22 Feb 2024 06:30:45 -0600 Subject: [PATCH] Add callApi wrapper to client to avoid unnecessary code dupe --- src/client.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/client.ts b/src/client.ts index d5dd0c0..6a6a8a8 100644 --- a/src/client.ts +++ b/src/client.ts @@ -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"; @@ -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( + fn: (api: NetsBloxApi) => Promise, + ): Promise { + try { + return await fn(this.api); + } catch (err) { + this.onerror(err); + throw err; + } + } + async fetch(url, opts?: RequestInit) { opts = opts || {}; url = this.url + url;