Home > Enterprise >  How to add getter with string method inside an object
How to add getter with string method inside an object

Time:11-16

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()}
 }
} 

CodePudding user response:

The syntax for getters is

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

CodePudding user response:

Not sure if that's what you wanted but you can use a Proxy

const configs = {
  header: new Proxy({
  }, {
    get() {
      return (Math.random() * 1000000 | 0).toString()
    }
  })
}

console.log(configs.header['x-some-id'])

  • Related