0

In my code below,

  • I'm calling the static "findAllPeople" method in my Person class. This method returns a set of Person objects.
  • The Person class also has a getter for fullName.

Problem: The res.json(Array.from(people))returns an array of the Person objects, but without the fullName property. When I debug Array.from(people)in VS Code it correctly returns the array of Person objects WITH the fullName property. But when I evaluate JSON.stringify(Array.from(people)), I get a String without the getter property.

I've already tried using [...people] instead of Array.from(people). But same result. So it's the stringify action which causes this problem (I assume ...).

How can I create a response which returns the array WITH the fullName property (based on the fullName getter)?

controller.js

const Person = require('./Person');

exports.getAll = function(req, res, next) {
    Person.findAllPeople()
        .then((people) => {
            res.json(Array.from(people));
        })
        .catch((err) => {return next(err);});
}

Person.js

class Person {
    constructor(personId, first, last, email, birthday) {
        this._id = personId ? personId : undefined;
        this.firstName = first ? first : undefined;
        this.lastName = last ? last : undefined;
        this.email = email ? email : undefined;
        this.birthday = birthday ? new Date(birthday) : undefined;
        this.relations = new Map();
    }
    get fullName() {
        return `${this.firstName} ${this.lastName}`;
    }
    static findAllPeople() {
        return personRepository.getAll("ONLY_NAMES")
            .then((people) => {
                people.forEach((person) => {
                    if (person.relations.size === 0) {
                        person.relations = undefined;
                    }
                })
                return people;
            })
            .catch(console.error);
    }
}
module.exports = Person;
bits
  • 672
  • 2
  • 7
  • 26

1 Answers1

1

Found the solution in JSON stringify ES6 class property with getter/setter

I just needed to add a toJSON method to my class...

toJSON() {
        return {
            _id: this._id,
            firstName: this.firstName,
            lastName: this.lastName,
            fullName: this.fullName,
            birthday: this.birthday,
            email: this.email,
            relations: this.relations
        }
    }
bits
  • 672
  • 2
  • 7
  • 26