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

Commit 070e205

Browse files
committed
refactor: promise first dns in browser
License: MIT Signed-off-by: Marcin Rataj <[email protected]>
1 parent 85ca250 commit 070e205

File tree

1 file changed

+21
-22
lines changed

1 file changed

+21
-22
lines changed

src/core/runtime/dns-browser.js

+21-22
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
const TLRU = require('../../utils/tlru')
55
const { default: PQueue } = require('p-queue')
66
const { default: ky } = require('ky-universal')
7+
const nodeify = require('promise-nodeify')
78

89
// Avoid sending multiple queries for the same hostname by caching results
910
const cache = new TLRU(1000)
@@ -26,38 +27,36 @@ const api = ky.create({
2627
const query = new URLSearchParams(new URL(response.url).search).toString()
2728
const json = await response.json()
2829
cache.set(query, json, ttl)
29-
return json
3030
}
3131
]
3232
}
3333
})
3434

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)
4038
}
4139

42-
module.exports = (domain, opts, callback) => {
40+
module.exports = (fqdn, opts = {}, cb) => {
4341
if (typeof opts === 'function') {
44-
callback = opts
42+
cb = opts
4543
opts = {}
4644
}
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)
5759
}
5860

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)
6362
}

0 commit comments

Comments
 (0)