1.0.7 • Published 7 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-resolver
API
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.id
mapResolver(map)
map
must be an filledobject
key
should be astring
, used as a flag, tellsresolver
whichfunction
to callvalue
must be afunction
that returns anobject
,array
orundefined
- return
resolver: (string[, string]) => any
Afunction
you call to resolve with flag and id for value.
resolver(flag, id)
flag
must be astring
and matches flags in themap
id
is an optionalstring
tells resolver what to resolveuseDotNotation
is an optionalboolean
indicates 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