Web3 Connection dropped by remote peer

hello guys … I’m working with nodejs, web3 and a moralis node to listen to events of a contract, at first everything goes well, but within a couple of hours, or 3 or even more time it gives me the following console bug…

Error: CONNECTION ERROR: The connection got closed with the close code `1006` and the following reason string `Connection drop,
code: 1006,
reason: 'Connection dropped by remote peer.

I have read in the case of infura, it is a normal behavior to disconnect inactive connections from the node, I don’t know if it is true, I found a supposed good practice to make the node reconnect when the connection is lost, the code is as follows… .

const refreshProvider = (web3Obj, providerUrl) => {
  let retries = 0

  const retry = (event) => {
    if (event) {
      debug('[WEB3] provider disconnected or errored.')
      retries += 1

      if (retries > 5) {
        debug(`[WEB3] Max retries of 5 exceeding: ${retries} times tried`)
        return setTimeout(refreshProvider, 5000)
    } else {
      debug(`[WEB3] Reconnecting web3 provider: ${retries} times tried`)
      refreshProvider(web3Obj, providerUrl)

    return null

  const provider = new Web3.providers.WebsocketProvider(providerUrl)

  provider.on('end', () => {
    debug('[WEB3] EVENT provider end')

    return retry()
  provider.on('error', () => {
    debug('[WEB3] EVENT provider error')

    return retry()


  debug('[WEB3] New Web3 provider initiated')

  return provider

refreshProvider(web3, process.env.NODE_MORALIS)

It really works, but in some cases it takes minutes to reconnect, and apart from that, after reconnecting it doesn’t listen to the events that are emitted. How could I avoid these disconnections? or if it is not possible how to make it reconnect in ms and after the reconnection it can listen to the events.