Skip to content

Commit

Permalink
Reject bad request response (livekit#124)
Browse files Browse the repository at this point in the history
* Reject bad request response

* refactor to async await

* Create clever-emus-remember.md

* More explicit status error
  • Loading branch information
lukasIO authored Dec 20, 2023
1 parent 43f540d commit f4407b3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 14 deletions.
5 changes: 5 additions & 0 deletions .changeset/clever-emus-remember.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"livekit-server-sdk": patch
---

Throw error on bad Twirp response status and use async/await instead of promise chaining for improved error catching
29 changes: 15 additions & 14 deletions src/TwirpRPC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,23 @@ export class TwirpRpc {
this.prefix = prefix || defaultPrefix;
}

request(service: string, method: string, data: any, headers?: any): Promise<any> {
async request(service: string, method: string, data: any, headers?: any): Promise<any> {
const path = `${this.prefix}/${this.pkg}.${service}/${method}`;
const url = new URL(path, this.host);
return new Promise<any>((resolve, reject) => {
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8',
...headers,
},
body: JSON.stringify(data),
})
.then(async (res) => {
resolve(camelcaseKeys(await res.json(), { deep: true }));
})
.catch(reject);

const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8',
...headers,
},
body: JSON.stringify(data),
});

if (!response.ok) {
throw new Error(`Request failed with status ${response.status}: ${response.statusText}`);
}
const parsedResp = await response.json();
return camelcaseKeys(parsedResp, { deep: true });
}
}

0 comments on commit f4407b3

Please sign in to comment.