1- /**
2- * Return appropriate error object for public API errors
3- *
4- * NOTE: Don't use this helper for APIs that may include sensitive data
5- * in error message or stacktrace.
6- */
1+ // Helpers for working with Trading Strategy public APIs
72import { type NumericRange , error } from '@sveltejs/kit' ;
83import { backendUrl } from '$lib/config' ;
94
105type Params = Record < string , string > ;
116
127const controllers : Record < string , AbortController > = { } ;
138
9+ /**
10+ * Fetch data from Trading Strategy backend endpoints
11+ *
12+ * @param fetch SvelteKit's fetch function
13+ * @param endpoint final path segment of endpoint, e.g.: 'chains', 'pairs'
14+ * @param params URL paramaters as a record of string values
15+ * @param abortPrevious set to true to abort pending requets to the same endpoint
16+ * @returns the deserialised JSON payload
17+ */
1418export async function fetchPublicApi ( fetch : Fetch , endpoint : string , params : Params = { } , abortPrevious = false ) {
1519 let signal : AbortSignal | undefined = undefined ;
1620
@@ -34,6 +38,12 @@ export async function fetchPublicApi(fetch: Fetch, endpoint: string, params: Par
3438 }
3539}
3640
41+ /**
42+ * Return appropriate error object for public API errors
43+ *
44+ * NOTE: Don't use this helper for APIs that may include sensitive data
45+ * in error message or stacktrace.
46+ */
3747export async function publicApiError ( response : Response ) {
3848 let status = response . status as NumericRange < 400 , 599 > ;
3949 if ( status >= 500 ) status = 503 ;
@@ -45,3 +55,32 @@ export async function publicApiError(response: Response) {
4555
4656 return error ( status , { message : response . statusText , stack } ) ;
4757}
58+
59+ /**
60+ * Factory function to generate an error handler that can be used when fetching
61+ * optional data in order to fall back gracefully instead of throwing an error.
62+ *
63+ * Logs error to stderr and fails w/out re-throwing.
64+ *
65+ * @example
66+ * ```typescript
67+ * import { optionalDataError } from '$lib/helpers/public-api';
68+ *
69+ * export async function load({ fetch }) {
70+ * return {
71+ * impressiveNumbers: await fetchPublicApi(fetch, 'impressive-numbers').catch(optionalDataError('impressive-numbers')),
72+ * posts: await getPosts(fetch).catch(optionalDataError('blog posts'))
73+ * };
74+ * }
75+ * ```
76+ *
77+ * @param dataType the type of data being requested, e.g.: 'impressive-numbers'
78+ * @returns error handler function that can be passed to Promise.catch
79+ */
80+ export function optionalDataError ( dataType ?: string ) {
81+ const errorIntro = dataType ? `Request for ${ dataType } failed` : 'Request failed' ;
82+ return ( err : Error ) => {
83+ console . error ( `${ errorIntro } ; rendering page without data.` ) ;
84+ console . error ( err ) ;
85+ } ;
86+ }
0 commit comments