1.0.7 • Published 9 years ago
map-resolver v1.0.7
map-resolver
Let you pass a map and return a resolver to resolve for value later
Installation
$ npm install map-resolverAPI
const mapResolver = require('map-resolver');
const map = {
    '@': () => req.body,
    ':': () => req.params,
    '?': () => req.query,
    '*': () => process.env,
    '#': () => req.cookies
};
const resolve = mapResolver(map);
const id = resolve('@', 'id');    //  id = req.body.id
const name = resolve(':0');    //  id = req.params[0]
const sid = resolve('?session.id');    //  sid = req.query.session.idmapResolver(map)
- mapmust be an filled- object
- keyshould be a- string, used as a flag, tells- resolverwhich- functionto call
- valuemust be a- functionthat returns an- object,- arrayor- undefined
- return resolver: (string[, string]) => anyAfunctionyou call to resolve with flag and id for value.
resolver(flag, id)
- flagmust be a- stringand matches flags in the- map
- idis an optional- stringtells resolver what to resolve
- useDotNotationis an optional- booleanindicates if id should be treat as dot notation
Example
const mapResolver = require('map-resolver');
var req = {};
const constants = {
    'maxThread': 3
};
const map = {
    '...': () => req.body,
    ':': () => req.params,
    '?': () => req.query,
    '*': () => process.env,
    '#': () => req.cookies,
    '定': () => constants,
};
const resolve = mapResolver(map);
req = {
    body: {
        'app.name': 'MP'
    },
    params: ['express', 'middleware'],
    query: {
        session: {
            id: '123'
        }
    }
};
process.env.YEAR = '2017';
console.log(resolve('...app.name', null, false));   //  'MP'
console.log(resolve(':1'));                         //  middleware
console.log(resolve('?session.id', null, true));    //  '123'
console.log(resolve('*', 'YEAR'));                  //  '2017'
console.log(resolve('#', 'id'));                    //  undefined;
console.log(resolve('定maxThread'));                //  3