Búsqueda de sitios web

javascript - ¿Cómo hacer que JSON.stringify sólo serialice los getters de TypeScript?


Tengo la siguiente estructura de clase:

export abstract class PersonBase {
    public toJSON(): string {
        let obj = Object.assign(this);
        let keys = Object.keys(this.constructor.prototype);
        obj.toJSON = undefined;
        return JSON.stringify(obj, keys);
    }
}

export class Person extends PersonBase {

    private readonly _firstName: string;
    private readonly _lastName: string;

    public constructor(firstName: string, lastName: string) {
        this._firstName = firstName;
        this._lastName = lastName;
    }

    public get first_name(): string {
        return this._firstName;
    }

    public get last_name(): string {
        return this._lastName;
    }
}

export class DetailPerson extends Person {

    private _address: string;

    public constructor(firstName: string, lastName: string) {
        super(firstName, lastName);
    }

    public get address(): string {
        return this._address;
    }
     
    public set address(addy: string) {
        this._address = addy;
    }
}

Estoy intentando que toJSON genere todos los getters (excluyendo propiedades privadas) de toda la jerarquía de objetos.

Entonces, si tengo una instancia de DetailPerson y llamo al método toJSON, quiero ver la siguiente salida:

{
   "address": "Some Address",
   "first_name": "My first name",
   "last_name": "My last name"
}

Usé una de las soluciones de esta pregunta y respuesta, pero no resuelve mi caso particular: no estoy obteniendo todos los getters en la salida.

¿Qué necesito cambiar aquí para obtener el resultado que estoy buscando?

Respuesta #1

El enlace que proporcionaste usa Object.keys, lo cual omite las propiedades en el prototipo.

Podrías usar for...in en lugar de Object.keys:

public toJSON(): string {
    let obj: any = {};

    for (let key in this) {
        if (key[0] !== '_') {
            obj[key] = this[key];
        }
    }

    return JSON.stringify(obj);
}

Editar: Este es mi intento de devolver solo getters, de manera recursiva, sin suponer que los no-getters comienzan con guiones bajos. Estoy seguro de que hay detalles que pasé por alto (referencias circulares, problemas con ciertos tipos), pero es un buen comienzo:

abstract class PersonBase {
  public toJSON(): string {
    return JSON.stringify(this._onlyGetters(this));
  }

  private _onlyGetters(obj: any): any {
    // Gotchas: types for which typeof returns "object"
    if (obj === null || obj instanceof Array || obj instanceof Date) {
      return obj;
    }

    let onlyGetters: any = {};

    // Iterate over each property for this object and its prototypes. We'll get each
    // property only once regardless of how many times it exists on parent prototypes.
    for (let key in obj) {
      let proto = obj;

      // Check getOwnPropertyDescriptor to see if the property is a getter. It will only
      // return the descriptor for properties on this object (not prototypes), so we have
      // to walk the prototype chain.
      while (proto) {
        let descriptor = Object.getOwnPropertyDescriptor(proto, key);

        if (descriptor && descriptor.get) {
          // Access the getter on the original object (not proto), because while the getter
          // may be defined on proto, we want the property it gets to be the one from the
          // lowest level
          let val = obj[key];

          if (typeof val === 'object') {
            onlyGetters[key] = this._onlyGetters(val);
          } else {
            onlyGetters[key] = val;
          }

          proto = null;
        } else {
          proto = Object.getPrototypeOf(proto);
        }
      }
    }

    return onlyGetters;
  }
}

Artículos relacionados