Created
March 18, 2021 19:47
-
-
Save burtonator/8e62d836ebb4d64dfeeb790c9b439d5c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type FetchResponseError = { | |
readonly code: 'fetch-response-error'; | |
readonly message: string; | |
readonly status: number; | |
readonly statusText: string; | |
}; | |
type FetchError = { | |
readonly code: 'fetch-error', | |
readonly message: string; | |
}; | |
export type CloudFunctionResponse<S, E> = S | E | FetchResponseError | FetchError; | |
export function getErrorFromCloudFunctionResponse(e: FetchResponseError | FetchError): Error { | |
throw new Error(e.message); | |
} | |
export async function executeCloudFunction<S, E>(cloudFunctionName: string, body: any): Promise<CloudFunctionResponse<S, E>> { | |
const url = `https://us-central1-polar-cors.cloudfunctions.net/${cloudFunctionName}/`; | |
const init: RequestInit = { | |
mode: "cors", | |
method: 'POST', | |
headers: { | |
"Content-Type": "application/json", | |
}, | |
redirect: 'follow', | |
body: JSON.stringify(body) | |
}; | |
// FIXME: Analytics.event2("CloudFunctionCalled", {name: cloudFunctionName}); | |
try { | |
const response = await fetch(url, init); | |
if (response.status === 200) { | |
return await response.json() as S; | |
} else { | |
const text = await response.text(); | |
try { | |
// this is a JSON error... | |
return JSON.parse(text) as E; | |
} catch (e) { | |
// if this is not json it's text/plain and so we should try to | |
// return a fetch-response-error | |
const error: FetchResponseError = { | |
code: "fetch-response-error", | |
message: response.statusText, | |
status: response.status, | |
statusText: response.statusText | |
}; | |
return error; | |
} | |
} | |
} catch (e) { | |
return { | |
code: 'fetch-error', | |
message: e.message | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment