i wonder how to create models in javascript ?
example Object user: should have these properties [name,username,password]
, and no other properties should be there.
now i want to send in any value it should return an objects with these 3 properties and ignore any other props.
i tried using
var UserFactory = props => ({
user :props.user||'',
username:props.username||'',
..etc
})
now when ever i pass user object arround im sure all properties does exists and no undefined error may occur.
reason i want this is to normalize data when fetching/posting to server.
is there an already best practice to how to do this ?
p.s: if it matters, i'm using this in a react-redux learning project ..
thanks
Edit problem with code above:
userFactory({}) instanceOf UserObject === false
so how to make sure if a variable is holding a userObject inside ?is there an already best practice to how to do this ?
Yes, and this is what you are doing - using object factories. It is a common approach in JS world when constructing new models. However, instead of using ES5 approach use ES6 approach of parameter handling:
let UserFactory = ({user='', username='', etc...}) => { ... }
See more here.