简体   繁体   中英

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

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 ?

ps: 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM