4
4
const TLRU = require ( '../../utils/tlru' )
5
5
const { default : PQueue } = require ( 'p-queue' )
6
6
const { default : ky } = require ( 'ky-universal' )
7
+ const nodeify = require ( 'promise-nodeify' )
7
8
8
9
// Avoid sending multiple queries for the same hostname by caching results
9
10
const cache = new TLRU ( 1000 )
@@ -26,38 +27,36 @@ const api = ky.create({
26
27
const query = new URLSearchParams ( new URL ( response . url ) . search ) . toString ( )
27
28
const json = await response . json ( )
28
29
cache . set ( query , json , ttl )
29
- return json
30
30
}
31
31
]
32
32
}
33
33
} )
34
34
35
- function unpackResponse ( response , callback ) {
36
- if ( response . Path ) {
37
- return callback ( null , response . Path )
38
- }
39
- return callback ( new Error ( response . Message ) )
35
+ const ipfsPath = ( response ) => {
36
+ if ( response . Path ) return response . Path
37
+ throw new Error ( response . Message )
40
38
}
41
39
42
- module . exports = ( domain , opts , callback ) => {
40
+ module . exports = ( fqdn , opts = { } , cb ) => {
43
41
if ( typeof opts === 'function' ) {
44
- callback = opts
42
+ cb = opts
45
43
opts = { }
46
44
}
47
- opts = opts || { }
48
-
49
- const searchParams = new URLSearchParams ( opts )
50
- searchParams . set ( 'arg' , domain )
51
-
52
- // try cache first
53
- const query = searchParams . toString ( )
54
- if ( ! opts . nocache && cache . has ( query ) ) {
55
- const response = cache . get ( query )
56
- return setImmediate ( ( ) => unpackResponse ( response , callback ) )
45
+ const resolveDnslink = async ( fqdn , opts = { } ) => {
46
+ const searchParams = new URLSearchParams ( opts )
47
+ searchParams . set ( 'arg' , fqdn )
48
+
49
+ // try cache first
50
+ const query = searchParams . toString ( )
51
+ if ( ! opts . nocache && cache . has ( query ) ) {
52
+ const response = cache . get ( query )
53
+ return ipfsPath ( response )
54
+ }
55
+
56
+ // fallback to delegated DNS resolver
57
+ const response = await _httpQueue . add ( ( ) => api . get ( 'dns' , { searchParams } ) . json ( ) )
58
+ return ipfsPath ( response )
57
59
}
58
60
59
- _httpQueue . add ( async ( ) => {
60
- const response = await api . get ( 'dns' , { searchParams } )
61
- setImmediate ( ( ) => unpackResponse ( response , callback ) )
62
- } ) . catch ( ( err ) => setImmediate ( ( ) => callback ( err ) ) )
61
+ return nodeify ( resolveDnslink ( fqdn , opts ) , cb )
63
62
}
0 commit comments