Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
What's the right way to declare an object in Node.js router

I'm trying to solve memory leaks in my Node.js app and seems this code does leak

const ApolloClient = require('apollo-client').ApolloClient;
const fetch = require('node-fetch');
const createHttpLink = require('apollo-link-http').createHttpLink;
const InMemoryCache = require('apollo-cache-inmemory').InMemoryCache;

const httpLink = createHttpLink({
  uri: 'http://xxxxxx',
  fetch: fetch
});

const client = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache()
});


module.exports = (app) => {
  app.post('/graphql', async (req, res, next) => {
    try {
        const data = await client.query({
            query: 'xxxxxxx',
            variables: 'xxxxxxx'
        });
        return res.json(data);
    } catch (err) {
      return next('error');
    }
  });
};

so ApolloClient client recreates every time since it's a global. Is it better to define it inside the route? Won't it cause performance issues then?

const ApolloClient = require('apollo-client').ApolloClient;
const fetch = require('node-fetch');
const createHttpLink = require('apollo-link-http').createHttpLink;
const InMemoryCache = require('apollo-cache-inmemory').InMemoryCache;

module.exports = (app) => {
  app.post('/graphql', async (req, res, next) => {
    try {
        let httpLink = createHttpLink({
            uri: 'http://xxxxxx',
            fetch: fetch
          });
          
          let client = new ApolloClient({
            link: httpLink,
            cache: new InMemoryCache()
          });

        const data = await client.query({
            query: 'xxxxxxx',
            variables: 'xxxxxxx'
        });

        httpLink = null
        client = null
        
        return res.json(data);
    } catch (err) {
      return next('error');
    }
  });
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Creating one ApolloClient instance and reusing it is better for many reasons.

  1. Minimum number of instances.

Consider having 20 or more (N) endpoints/middlewares that needs to access some data that is stored in your database. Creating an ApolloClient instance for each one would mean N number of instances. This is not performant and violates and violates the 'Do not repeat yourself' coding rule.

On the other hand creating one instance and using it throughout the app is very handy. Consider this example:

const ApolloClient = require('apollo-client').ApolloClient;
const fetch = require('node-fetch');
const createHttpLink = require('apollo-link-http').createHttpLink;
const InMemoryCache = require('apollo-cache-inmemory').InMemoryCache;

const httpLink = createHttpLink({
  uri: 'http://xxxxxx',
  fetch: fetch
});

// instantiating
module.exports = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache()
});

a module:

const dbClient = require('./db_client')

module.exports = (app) => {
  app.post('/graphql', async (req, res, next) => {
    try {
        const data = await dbClient.query({
            query: 'xxxxxxx',
            variables: 'xxxxxxx'
        });
        return res.json(data);
    } catch (err) {
      return next('error');
    }
  });
};

another module:

const dbClient = require('./db_client')
...

another module:

const dbClient = require('./db_client')
...

As can be seen, with just one instance we can achieve a more robust and performant application.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda