Meteor-Community-Packages / meteor-simple-schema

Meteor integration package for simpl-schema
https://github.com/Meteor-Community-Packages/meteor-simple-schema
MIT License
920 stars 162 forks source link

Idiomatic way to initialize/forge objects #169

Closed silently closed 9 years ago

silently commented 9 years ago

Hello,

Maybe if I've missed the idiomatic way to do this in simple-schema: initialize an object with all the fields declared in the schema, and their value set to either undefined or a given value (if defaultValue or autoValue are defined).

I mean something like:

var personSchema = new SimpleSchema({
  name: {
    type: String,
    label: "name",
    defaultValue: "Cary"
  },
  nickname: {
    type: String,
    label: "nickname"
  }
});
var p = personSchema.forge();// { name: "Cary", nickname: undefined }

It would have 2 added values upon:

var p = personSchema.clean({});// { name: "Cary" }

This would be very practical to initialize forms for example (I know about autoform but maybe autoform should not be a requirement).

Thanks!

aldeed commented 9 years ago

Why do you want an undefined value in the object? You're saying you want to be able to loop through the props to create a form? I can't see that being too useful. Creating a form would require looping through the schema object anyway, like autoform does, because you need to know the type.

silently commented 9 years ago

I have created the forms manually (type text/email etc.) and so having a simple object with good autoValue functions evaluated would fit with this approach. I think it makes sense in certain cases.

But yes, if I'd wanted to generate the form automatically like autoform, I'd be stuck with props type. The official way to do so is to iterate on objectKeys?

silently commented 9 years ago

For the case I've suggested (manually created forms with explicit input html), I think:

var p = personSchema.clean({});// { name: "Cary" }

is enough functionally.

I still think the "forge" semantics can be interesting, especially if autoValue functions give random values (thanks to chancejs for example). It can be useful for testing purposes, or in my case I develop a prototype and I wanted random/fake data.

I guess the proposal need more traction from others, or will be archived!

aldeed commented 9 years ago

This feels like it would be best as a separate add-on package, which you're welcome to create, since the use cases would be fairly limited. I do agree it could be useful at times, though.