Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

npm module function interception. specifically base module 'dns'

import DNS from 'dns'

DNS.resolveTxt('test-website.com', (err, addresses) => {
      console.log(err, addresses);
})

Above would be an example usage of how the node resolves a web address. I want to build a nock library for 'dns', and intercept the handler. (This would be used in the AWS nock library I've created for Route53, so this is not for "testing" purposes). I'm seeing some rewiremock stuff that makes sense, but that seems like a testing mocking tool. Is there anyway to achieve this interception? Rather than just intercepting it in between and moving over to the original method, I want to figure out how to replace the whole handler itself. *

Clarification: I want to use DNS.resolveTxt directly and the addresses I get from the response will be my custom.

Clarification #2: I want to ideally nock the whole DNS library. resolveTxt is just an example.

Clarification #3: I want do mock the DNS globally across my service. Not just for a single use.

Clarification #4 (important): I think my question is how I can intercept the tcp requests to the DNS. sudo tcpdump host 1.1.1.1 shows the current calls to the DNS server set from my computer. If I were to dns.setServer('1.2.3.4') for example, and do a sudo tcpdump host 1.2.3.4, every time I call DNS.resolveTxt, I am able to see the call logs. Any idea how to intercept that?

like image 210
gatsbyz Avatar asked Oct 27 '22 15:10

gatsbyz


1 Answers

You can implement your own lookup function that mimics DNS.Resolver#lookup()

https://nodejs.org/docs/latest-v12.x/api/dns.html#dns_dns_lookup_hostname_options_callback

And pass it in the options to node module functions which take TCP connection options.

https://nodejs.org/docs/latest-v12.x/api/http.html#http_http_request_options_callback

https://nodejs.org/docs/latest-v12.x/api/net.html#net_socket_connect_options_connectlistener

like image 76
leitning Avatar answered Nov 09 '22 15:11

leitning