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

Commit 7d82d34

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

File tree

1 file changed

+21
-21
lines changed

1 file changed

+21
-21
lines changed

src/core/runtime/dns-browser.js

+21-21
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)
@@ -32,32 +33,31 @@ const api = ky.create({
3233
}
3334
})
3435

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)
4039
}
4140

42-
module.exports = (domain, opts, callback) => {
41+
module.exports = (fqdn, opts = {}, cb) => {
4342
if (typeof opts === 'function') {
44-
callback = opts
43+
cb = opts
4544
opts = {}
4645
}
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)
5760
}
5861

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

0 commit comments

Comments
 (0)