mekanika / skematic

Data model & rule engine for JS objects
9 stars 0 forks source link

Flag and map primary key fields #17

Closed cayuu closed 9 years ago

cayuu commented 9 years ago

Provide a means to flag a field as being the primary key/identifier-field. Something like:

var propSchema = {
  prop_id: {primaryKey:true},
  name: {type:"string"}
};

This could be coupled with generate to make a particular kind of id. If no generate is present then an adapter should map the default primary key field to this field name. The above may be stored in the db as:

_id name
512314 power
519910 speed

A default response from the data store would be:

[ {_id:"512314", name:"power"}, {_id:"519910", name:"speed"} ]

But given the Skematic prop_id primary key declaration, this should map to:

[ {prop_id:"512314", name:"power"}, {prop_id:"519910", name:"speed"} ]

Building this map capability into Skematic could look something like (needs consideration):

Skematic.format( propSchema, {mapPrimaryFrom:"_id"}, data );
cayuu commented 9 years ago

So what's the opts flag to use for this? mapPrimaryFrom is pretty clear about what it's doing, and could probably only be clarified further by making it mapPrimaryKeyFromField, which is ugly and verbose. One other shorter alternative is either mapIdFrom or mapKeyFrom. The 'key' concept is a little vague though as this is often used to mean "field" or "property".

Keeping it "active" means keeping map in there. Keeping from in there is handy to indicate what the content should be (rather than leaving you wondering "is mapKey a boolean"). So the only thing that's left is the "what", and that's gonna either be "primary" or "id".

"Id" it is: mapIdFrom.

cayuu commented 9 years ago

Docs example:


A schema can declare any one of its fields as the primary key (the id field) to be used for its data objects. This can be used in conjunction with Skematic.format() in order to modify an incoming data collection and map a pre-existing id field (say for example "_id") to the primaryKey.

This is useful for data stores that use their own id fields (eg. MongoDB uses "_id").

var propSchema = {
  prop_id: {primaryKey:true},
  name: {type:"string"}
};

// Example default results from data store:
var data = [ {_id:"512314", name:"power"}, {_id:"519910", name:"speed"} ];

Skematic.format( propSchema, {mapIdFrom:'_id'}, data );
// -> [ {prop_id:"512314", name:"power"}, {prop_id:"519910", name:"speed"} ]