Skip to content
Advertisement

How to add getter with string method inside an object

I have an object called headers. Inside which I want to add certain headers with some random value like:

configs = {
 header : {
   'x-some-id': Math.random().toString()
 }
} 

The config paramter is used to client which is used to send http requests. And the randomid is some id generated by a load balancer. So it will we different for every request. We dont want to create a new client for every client, hence I want to use getter function in header so that everytime a request is made, the header is automatically populated with a new id. How do I implement this using getters. ideally this is what I what to achieve:

configs = {
 header : {
   'x-some-id': get() { return Math.random().toString()}
 }
} 

Advertisement

Answer

The syntax for getters is

configs = {
  header: {
    get 'x-some-id'() { return Math.random().toString(); },
  },
};
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement