|
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)
|
@@ -32,32 +33,31 @@ const api = ky.create({
|
32 | 33 | }
|
33 | 34 | })
|
34 | 35 |
|
35 |
| -function unpackResponse (response, callback) { |
36 |
| - if (response.Path) { |
37 |
| - return callback(null, response.Path) |
38 |
| - } |
39 |
| - return callback(new Error(response.Message)) |
| 36 | +const ipfsPath = (response) => { |
| 37 | + if (response.Path) return response.Path |
| 38 | + throw new Error(response.Message) |
40 | 39 | }
|
41 | 40 |
|
42 |
| -module.exports = (domain, opts, callback) => { |
| 41 | +module.exports = (fqdn, opts = {}, cb) => { |
43 | 42 | if (typeof opts === 'function') {
|
44 |
| - callback = opts |
| 43 | + cb = opts |
45 | 44 | opts = {}
|
46 | 45 | }
|
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)) |
| 46 | + const resolveDnslink = async (fqdn, opts = {}) => { |
| 47 | + const searchParams = new URLSearchParams(opts) |
| 48 | + searchParams.set('arg', fqdn) |
| 49 | + |
| 50 | + // try cache first |
| 51 | + const query = searchParams.toString() |
| 52 | + if (!opts.nocache && cache.has(query)) { |
| 53 | + const response = cache.get(query) |
| 54 | + return ipfsPath(response) |
| 55 | + } |
| 56 | + |
| 57 | + // fallback to delegated DNS resolver |
| 58 | + const response = await _httpQueue.add(() => api.get('dns', { searchParams })) |
| 59 | + return ipfsPath(response) |
57 | 60 | }
|
58 | 61 |
|
59 |
| - _httpQueue.add(async () => { |
60 |
| - const response = await api.get('dns', { searchParams }) |
61 |
| - setImmediate(() => unpackResponse(response, callback)) |
62 |
| - }).catch((err) => setImmediate(() => callback(err))) |
| 62 | + return nodeify(resolveDnslink(fqdn, opts), cb) |
63 | 63 | }
|
0 commit comments