Skip to content
This repository has been archived by the owner on Feb 12, 2024. It is now read-only.

Commit

Permalink
refactor: promise first dns in browser
Browse files Browse the repository at this point in the history
License: MIT
Signed-off-by: Marcin Rataj <lidel@lidel.org>
  • Loading branch information
lidel committed Jul 31, 2019
1 parent 85ca250 commit 070e205
Showing 1 changed file with 21 additions and 22 deletions.
43 changes: 21 additions & 22 deletions src/core/runtime/dns-browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -26,38 +27,36 @@ const api = ky.create({
const query = new URLSearchParams(new URL(response.url).search).toString()
const json = await response.json()
cache.set(query, json, ttl)
return json
}
]
}
})

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 }).json())
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)
}

0 comments on commit 070e205

Please sign in to comment.