FirstOfMany FirstOfMany - 5 months ago 16
Node.js Question

Add an array property to this Express.js model class

What specific changes need to be made to the code below in order to successfully add a property that is an array of Strings to a JavaScript model object in an Express.js app? The

AppUser
code is placed in a new
appuser.js
file in the
/app/models
directory of this GitHub link
.

Here is the code for the
AppUser
class, including placeholders for the getters and setters for the array, which this OP asks how to write:

var method = AppUser.prototype;

function AppUser(name) {
this._name = name;
}

method.getName = function() {
return this._name;
};

//scopes
method.getScopes = function() {
//return the array of scope string values
};
method.setScopes = function(scopes) {
//set the new scopes array to be the scopes array for the AppUser instance
//if the AppUser instance already has a scopes array, delete it first
};
method.addScope = function(scope) {
//check to see if the value is already in the array
//if not, then add new scope value to array
};
method.removeScope = function(scope) {
//loop through array, and remove the value when it is found
}

module.exports = AppUser;

Answer

You could use class in ES6 like this :

'use strict';
module.exports = class AppUser {
  constructor(name) {
    this.name = name;
    this.scopes = [];
  }
  getName() {
    return this.name;
  }
  getScopes() {
    return this.scopes;
  }
  addScope(scope){
    if (this.scopes.indexOf(scope) === -1) this.scopes.push(scope);
  }
}