diff --git a/src/workspaces/hooks/src/useClient.ts b/src/workspaces/hooks/src/useClient.ts index ddd18f8e..df766d54 100644 --- a/src/workspaces/hooks/src/useClient.ts +++ b/src/workspaces/hooks/src/useClient.ts @@ -53,6 +53,13 @@ export const getHeaders = (isText: boolean = false) => { return headers; }; +// 2xx responses can legitimately carry no body (201 Created / 204 No Content). res.json() throws on an +// empty body, so read text first and only parse when there's something — otherwise resolve undefined. +const parseBody = async (res: Response): Promise => { + const text = await res.text(); + return (text ? JSON.parse(text) : undefined) as T; +}; + export const getText = async (uri: string, baseUrl = '') => { const headers = getHeaders(true); const theUrl = baseUrl ? `${baseUrl}/${uri.replace(/^\//, '')}` : uri; @@ -67,8 +74,7 @@ export const get = async (uri: string, baseUrl = '') => { const theUrl = baseUrl ? `${baseUrl}/${uri.replace(/^\//, '')}` : uri; const res = await fetch(theUrl, { headers }); await validateResponse(res); - const data = await res.json(); - return data as T; + return parseBody(res); }; export const getBlob = async (uri: string, baseUrl = '') => { @@ -100,8 +106,7 @@ export const post = async (uri: string, payload?: any, baseUrl = '') => { headers, }); await validateResponse(res); - const data = await res.json(); - return data as T; + return parseBody(res); }; export const put = async (uri: string, payload?: any, baseUrl = '') => { @@ -119,8 +124,7 @@ export const put = async (uri: string, payload?: any, baseUrl = '') => { headers, }); await validateResponse(res); - const data = await res.json(); - return data as T; + return parseBody(res); }; export const patch = async (uri: string, payload?: any, baseUrl = '') => { @@ -132,8 +136,7 @@ export const patch = async (uri: string, payload?: any, baseUrl = '') => { headers, }); await validateResponse(res); - const data = await res.json(); - return data as T; + return parseBody(res); }; export const DELETE = async (uri: string, payload?: any, baseUrl = '') => { @@ -145,8 +148,7 @@ export const DELETE = async (uri: string, payload?: any, baseUrl = '') => { headers, }); await validateResponse(res); - const data = await res.json(); - return data as T; + return parseBody(res); }; const validateResponse = async (res: Response) => {