I am getting worried I have some terrible design pattern here in JS/Node.js/MongoDB. It seems to that to create an object, I need an object that looks like that object. This includes data that comes from the user or data that comes from the database. It is just a lot of duplication, but I have not figured another way around it.
Quick example
// Application user object
class User {
// Right away, my constructor almost literally takes itself as params
// The alternative being many setters
constructor({
username = '',
password = '',
email = ''
}){
this.username = username;
this.password = password;
this.email = email;
}
}
// Form data from REST API
const formdata = {
username: 'bob',
password: '123',
email: '[email protected]'
}
// Create the user in the app
const user = new User(formdata);
// Add to the db
insertIntoDb(user);
// Get from the db
const dbdata = getFromDb(userid);
// Turn into object
const user = new User(dbdata);
Maybe I am overthinking things. But my User
class barely does anything to begin with. Is it acceptable if this class is just a definition of an object (kind of like a c struct) so developers know what its properties should be? This is mostly the point I think. Since JS is so loose, you could set object properties to whatever you want or read properties that don't even exist (which I usually solve by adding getters).
But I get this headache when I realize that most, if not all, of these user properties are just for persistence. Should this be part of a persistence layer only?
isAdmin()
which returns true ifthis.level = 1
. Other than that there are a just a few getters and setters that I only wrote as needed. I hate how JS gives us this inanely powerful dot notation anything goes style, but we aren't really allowed to use it.