MCPcopy Index your code
hub / github.com/atomicdata-dev/atomic-data-browser / fetchResource

Function fetchResource

lib/src/client.ts:26–87  ·  view source on GitHub ↗
(
  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,
)

Source from the content-addressed store, hash-verified

24 * Does not add it to the store. If you need that, use `Store.fetchResource`.
25 */
26export 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 }

Callers 3

fetchResourceMethod · 0.90
checkPublicKeyMethod · 0.90
client.test.tsFile · 0.90

Calls 7

setErrorMethod · 0.95
parseJsonADResourceFunction · 0.90
tryValidURLFunction · 0.85
signRequestFunction · 0.85
getAgentMethod · 0.80
setMethod · 0.80
addResourceMethod · 0.80

Tested by

no test coverage detected