hapipal / confidence

Dynamic, declarative configurations
Other
263 stars 43 forks source link

Support for default criteria #65

Closed federicojasson closed 5 years ago

federicojasson commented 7 years ago

It would be useful to be able to define a default criteria.

Currently, when one calls get without a criteria, {} is used by default. I find myself repeating the same criteria every time I have to get a path:

store.get('/a/b', { env: process.env.NODE_ENV });

...

// At some other place
store.get('/c', { env: process.env.NODE_ENV });

If the criteria is more complex, things get more tedious. My workaround is to simply get the root config once and use that everywhere, but that eliminates the advantages of the get function.

patrickkettner commented 7 years ago

+1 for the feature idea. If anyone wants to implement before I get a chance to, I'll be happy to review/merge.

federicojasson commented 7 years ago

In order to keep backward compatibility, interfaces could be changed to:


new Store([document], [defaultCriteria])

By default, defaultCriteria is {}.


store.load(document, [defaultCriteria])

By default, defaultCriteria is {}.


store.get(key, [criteria])

By default, criteria is defaultCriteria.


store.meta(key, [criteria])

By default, criteria is defaultCriteria.


This way, if defaultCriteria is not passed, {} will used as the default criteria (as before).

ryanwilliamquinn commented 7 years ago

You could achieve this through partial application too, not sure this is enough of a solution:

const confidence = require('confidence')
const _ = require('lodash')
const manifest = {
  mykey: {
    $filter: 'env',
    production: 'prod',
    development: 'dev',
    $default: 'dflt'
  }
}
const criteria = {
  env: process.env.NODE_ENV
}
const store = new confidence.Store(manifest)
const storeGet = _.partialRight(store.get.bind(store), criteria)
console.log(`get mykey: ${storeGet('/mykey')}`)
augnin commented 5 years ago

you can do this by extending the Store class

const { Store } = require('confidence');
const Hoek = require('hoek');

module.exports = class extends Store {

    get(key, criteria) {

        return super.get(key, Hoek.applyToDefaults({ env: process.env.NODE_ENV }, criteria || {}));
    }
};
augnin commented 5 years ago

with $env feature, you can refer to environment variables in the store itself, without the need to pass them in criteria.

https://github.com/hapijs/confidence#filters