( subject: string, /** * Pass the Store if you want to directly add the resource (and its possible * nested child Resources) to the Store. */ store?: Store, /** * Pass a server URL if you want to use the `/path` endpoint to indirectly * fetch through that server. */ from?: string, )
| 24 | * Does not add it to the store. If you need that, use `Store.fetchResource`. |
| 25 | */ |
| 26 | export async function fetchResource( |
| 27 | subject: string, |
| 28 | /** |
| 29 | * Pass the Store if you want to directly add the resource (and its possible |
| 30 | * nested child Resources) to the Store. |
| 31 | */ |
| 32 | store?: Store, |
| 33 | /** |
| 34 | * Pass a server URL if you want to use the `/path` endpoint to indirectly |
| 35 | * fetch through that server. |
| 36 | */ |
| 37 | from?: string, |
| 38 | ): Promise<Resource> { |
| 39 | let resource = new Resource(subject); |
| 40 | try { |
| 41 | tryValidURL(subject); |
| 42 | const requestHeaders: HeadersObject = {}; |
| 43 | requestHeaders['Accept'] = 'application/ad+json'; |
| 44 | // Sign the request if there is an agent present |
| 45 | store && |
| 46 | store.getAgent() && |
| 47 | (await signRequest(subject, store.getAgent(), requestHeaders)); |
| 48 | let url = subject; |
| 49 | if (from !== undefined) { |
| 50 | const newURL = new URL(`${from}/path`); |
| 51 | newURL.searchParams.set('path', subject); |
| 52 | url = newURL.href; |
| 53 | } |
| 54 | if (fetch == undefined) { |
| 55 | throw new AtomicError( |
| 56 | `No window object available this lib currently requires the DOM for fetching`, |
| 57 | ); |
| 58 | } |
| 59 | const response = await fetch(url, { |
| 60 | headers: requestHeaders, |
| 61 | }); |
| 62 | const body = await response.text(); |
| 63 | if (response.status == 200) { |
| 64 | try { |
| 65 | const json = JSON.parse(body); |
| 66 | resource = parseJsonADResource(json, resource, store); |
| 67 | } catch (e) { |
| 68 | throw new AtomicError( |
| 69 | `Could not parse JSON from fetching ${subject}. Is it an Atomic Data resource? Error message: ${e.message}`, |
| 70 | ); |
| 71 | } |
| 72 | } else if (response.status == 401) { |
| 73 | throw new AtomicError( |
| 74 | `You don't have the rights to do view ${subject}. Are you signed in with the right Agent? More detailed error from server: ${body}`, |
| 75 | ErrorType.Unauthorized, |
| 76 | ); |
| 77 | } else { |
| 78 | const error = new AtomicError(`${response.status} error: ${body}`); |
| 79 | resource.setError(error); |
| 80 | } |
| 81 | } catch (e) { |
| 82 | resource.setError(e); |
| 83 | } |
no test coverage detected