const async_hooks = require('async_hooks');
const fs = require('fs');
const http = require('http');
const fetch = require('node-fetch');

const asyncHook = async_hooks.createHook({
    init: (asyncId, type, triggerAsyncId, resource) => {
      if(type === 'TCPCONNECTWRAP') {
        process.nextTick(() => {
            console.log('TCPCONNECTWRAP');
            // Unable to set header here (happens after TCPWRAP And socket:lookup)
        });
      }

      if(type === 'TCPWRAP') {
        process.nextTick(() => {
            console.log(`${type} ${resource}`);
            const socket = resource.owner;
            socket.once('lookup', () => {
                console.log('lookup');

                //Not allowed
                //socket.parser.outgoing.setHeader('User-Agent', 'boss');
                //---
                
            });
            socket.once('data', () => {
                // Pick up headers from incomming request!
                if(socket.parser.incoming) {
                    console.log('Incomming user-agent: ' + socket.parser.incoming.headers['user-agent']);
                }
            });
        });
        
      }
    }
  });

asyncHook.enable();

http.createServer((req, res) => {
    callAPI(() => {
        res.end('hello\n');    
    })
}).listen(5000);

function callAPI(cb) {
    fetch('http://localhost:3000', {
        headers: { 'User-Agent': 'wrong - should be set' },
    }).then(r => {
        cb();
    })
}