how to create a model in javascript to make sure all properties does exists

Zalaboza picture Zalaboza · Apr 15, 2017 · Viewed 8.3k times · Source

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:

  1. i cannot do type check because what factory returns is a plain object not instance of a model userFactory({}) instanceOf UserObject === false so how to make sure if a variable is holding a userObject inside ?
  2. its verbose, yet if i use Object.assign(), i might get unwanted properties in my object, so i'm not sure if this is best way to do it.

Answer

Max Koretskyi picture Max Koretskyi · Apr 15, 2017

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.