diff --git a/src/core/runtime/dns-browser.js b/src/core/runtime/dns-browser.js index 0a202d3ef6..61d6539fc6 100644 --- a/src/core/runtime/dns-browser.js +++ b/src/core/runtime/dns-browser.js @@ -4,6 +4,7 @@ const TLRU = require('../../utils/tlru') const { default: PQueue } = require('p-queue') const { default: ky } = require('ky-universal') +const nodeify = require('promise-nodeify') // Avoid sending multiple queries for the same hostname by caching results const cache = new TLRU(1000) @@ -32,32 +33,31 @@ const api = ky.create({ } }) -function unpackResponse (response, callback) { - if (response.Path) { - return callback(null, response.Path) - } - return callback(new Error(response.Message)) +const ipfsPath = (response) => { + if (response.Path) return response.Path + throw new Error(response.Message) } -module.exports = (domain, opts, callback) => { +module.exports = (fqdn, opts = {}, cb) => { if (typeof opts === 'function') { - callback = opts + cb = opts opts = {} } - opts = opts || {} - - const searchParams = new URLSearchParams(opts) - searchParams.set('arg', domain) - - // try cache first - const query = searchParams.toString() - if (!opts.nocache && cache.has(query)) { - const response = cache.get(query) - return setImmediate(() => unpackResponse(response, callback)) + const resolveDnslink = async (fqdn, opts = {}) => { + const searchParams = new URLSearchParams(opts) + searchParams.set('arg', fqdn) + + // try cache first + const query = searchParams.toString() + if (!opts.nocache && cache.has(query)) { + const response = cache.get(query) + return ipfsPath(response) + } + + // fallback to delegated DNS resolver + const response = await _httpQueue.add(() => api.get('dns', { searchParams })) + return ipfsPath(response) } - _httpQueue.add(async () => { - const response = await api.get('dns', { searchParams }) - setImmediate(() => unpackResponse(response, callback)) - }).catch((err) => setImmediate(() => callback(err))) + return nodeify(resolveDnslink(fqdn, opts), cb) }