hapipal / confidence

Dynamic, declarative configurations
Other
264 stars 44 forks source link

Is it possible to add a key to an object depending on a value ? #42

Closed netei closed 9 years ago

netei commented 9 years ago

I would like to have conditionally add the "blipp" subobject to my "plugins" object with a filter.

Have as a result when phase=LOCAL:

"plugins": {
  "blipp": {
    "showAuth": true
  },
  "other": {
  }
}

Have as a result when phase!=LOCAL:

"plugins": {
  "other": {
  }
}
mtharrison commented 9 years ago

Have a look at filters. I think something like this will work:

var Confidence = require('confidence');

var config = {
    plugins: {
        '$filter': 'phase',
        '$default': { },
        '$base': {
            other: { }
        },
        local: {
            blipp: {
                showAuth: true
            }
        }
    }
}

var store = new Confidence.Store(config);

console.log(store.get('/', { phase: 'local' }));          // { plugins: { other: {}, blipp: { showAuth: true } } }
console.log(store.get('/', { phase: 'something-else' })); // { plugins: { other: {} } }
patrickkettner commented 9 years ago

thanks, @mtharrison - that is exactly the way to do this.

lemme know if you have any question, @netei

netei commented 9 years ago

Thanks that works well. I wasn't aware of the "$base" key, or at least didn't thought about it.

netei commented 9 years ago

Is it possible to do the same with arrays ?

Eg

var config = {
    plugins: {
        '$filter': 'phase',
        '$default': [{"key2":"val2"}],
        '$base':  [{"key1":"val1"}],
        local:  [{"key3":"val3"}],
    }
}

and have as a result the concatenated arrays ?

netei commented 9 years ago

It seems that it isn't possible with the current implementation to do that. Would you accept a pull request that would allow for this ?

patrickkettner commented 9 years ago

Almost certainly, but I am not quire sure what you expect the value to be - the arrays being merged?

netei commented 9 years ago

I would expect to get

console.log(store.get('/', { phase: 'local' }));
// [{"key1": "val1"}, {"key3", : "val3"}]

console.log(store.get('/', { phase: 'other' }));
// [{"key1": "val1"}, {"key2", : "val2"}]
patrickkettner commented 9 years ago

yeah, PR for that would be good