Home > Blockchain >  What happens if you send an instance of an ES6 class via REST API?
What happens if you send an instance of an ES6 class via REST API?

Time:08-04

class Data {

  #some_private_var

  constructor(private_val, regular_val) {
    this.regular_var = regular_val
    this.#some_private_var = private_val
  }
}

For example, if I use Axios to make an API request with an instance of the above class as the body of the request, what gets send over to the server?

Will #some_private_var get sent over?

What if a getter method is defined like so:

  get some_private_var() {
    return this.#some_private_var
  }

CodePudding user response:

Axios by default serialises JavaScript objects via JSON.stringify().

You can easily see what the result of that would be. The behaviour of which is defined here...

All the other Object instances [...] will have only their enumerable properties serialized.

class Data {

  #some_private_var

  constructor(private_val, regular_val) {
    this.regular_var = regular_val;
    this.#some_private_var = private_val;
  }
}

console.log(JSON.stringify(new Data("private", "regular")));

Private properties and methods are not enumerable properties.

If you want to expose members that would otherwise be hidden, create a toJSON() method

If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized

class Data {

  #some_private_var

  constructor(private_val, regular_val) {
    this.regular_var = regular_val;
    this.#some_private_var = private_val;
  }
  
  toJSON() {
    return {
      ...this,
      some_private_var: this.#some_private_var
    };
  }
}

console.log(JSON.stringify(new Data("private", "regular")));

  • Related