@@ -6,19 +6,27 @@ import { LinkIndexer } from 'linkdex'
6
6
import { carCode } from './constants'
7
7
import { Shard } from './api'
8
8
9
- export const fetchCAR = async ( root : UnknownLink ) : Promise < Shard > => {
10
- const res = await fetch ( `https://w3s.link/ipfs/${ root } ?format=car` )
11
- if ( ! res . ok ) throw new Error ( 'failed to get DAG as CAR' , { cause : { status : res . status } } )
12
- const bytes = new Uint8Array ( await res . arrayBuffer ( ) )
13
- // Verify CAR is complete
14
- const iterator = await CarBlockIterator . fromBytes ( bytes )
15
- const index = new LinkIndexer ( )
16
- for await ( const block of iterator ) {
17
- index . decodeAndIndex ( block )
18
- }
19
- if ( ! index . isCompleteDag ( ) ) {
20
- throw new Error ( 'CAR does not contain a complete DAG' )
9
+ export const fetchCAR = async ( root : UnknownLink , options ?: { timeout ?: number } ) : Promise < Shard > => {
10
+ const controller = new AbortController ( )
11
+ const timeoutID = setTimeout ( ( ) => controller . abort ( ) , options ?. timeout ?? 30_000 )
12
+ try {
13
+ const res = await fetch ( `https://w3s.link/ipfs/${ root } ?format=car` , { signal : controller . signal } )
14
+ if ( ! res . ok ) throw new Error ( 'failed to get DAG as CAR' , { cause : { status : res . status } } )
15
+ clearTimeout ( timeoutID )
16
+
17
+ const bytes = new Uint8Array ( await res . arrayBuffer ( ) )
18
+ // Verify CAR is complete
19
+ const iterator = await CarBlockIterator . fromBytes ( bytes )
20
+ const index = new LinkIndexer ( )
21
+ for await ( const block of iterator ) {
22
+ index . decodeAndIndex ( block )
23
+ }
24
+ if ( ! index . isCompleteDag ( ) ) {
25
+ throw new Error ( 'CAR does not contain a complete DAG' )
26
+ }
27
+ const link = Link . create ( carCode , await sha256 . digest ( bytes ) )
28
+ return { link, size : async ( ) => bytes . length , bytes : async ( ) => bytes }
29
+ } finally {
30
+ clearTimeout ( timeoutID )
21
31
}
22
- const link = Link . create ( carCode , await sha256 . digest ( bytes ) )
23
- return { link, size : async ( ) => bytes . length , bytes : async ( ) => bytes }
24
32
}
0 commit comments