M
M
motomac2018-02-07 13:40:03
Node.js
motomac, 2018-02-07 13:40:03

Will there be a memory leak?

I'm writing a small API gateway in Express. The server receives an HTTP request, reads the token, and makes several requests to the main REST API, supplying each with this token.
In order not to call each method from the api module with a token, I use the constructor and ES6 classes. But there were doubts about the correctness of my approach. Doesn't it smell like uncontrolled creation of instances of the Api class with multiple requests from different clients and subsequent memory leaks?
Well, in general, can there be a more elegant way to organize the code?

// index.js
const Api = require('./api')

app.get('/forward_to_api', function (req, res) {
  let api = new Api(res.locals.token)

  api.getSomething('something')
    .then(response => ...)
    .catch(error => console.log(`Error: ${error.message}`))

  api.getSomethingNew('somethingNew')
    .then(response => ...)
    .catch(error => console.log(`Error: ${error.message}`))
})

// api.js
module.exports = class Api {
  constructor(token) {
    this.config = {
      headers: { 'Authorization': `Bearer ${token}` }
    }
  }

  getSomething(name) {
    return axios.get(`/api/something/${name}`, this.config)
  }

  getSomethingNew(name) {
    return axios.get(`/api/something_new/${name}`, this.config)
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vit, 2018-02-07
@motomac

First, there will be no memory leaks, the garbage collector will take care of everything.
But, secondly, your code as a whole is very strange.
You receive one request to /forward_to_api, inside you make two parallel requests. As soon as one of them works out, you send a response to the client and close the connection with it. Do you understand that when the second request completes, it will have nowhere to send its status 204? What is the meaning of such code?

C
Coder321, 2018-02-07
@Coder321

If you are really afraid, then create one instance and pass the token to the methods.
At the extreme, it can nullify the instance when the method completes.
But as Vit said , there will be no leaks, because when the method completes its api instance will be deleted by the collector.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question