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 filledobjectkeyshould be astring, used as a flag, tellsresolverwhichfunctionto callvaluemust be afunctionthat returns anobject,arrayorundefined- return
resolver: (string[, string]) => anyAfunctionyou call to resolve with flag and id for value.
resolver(flag, id)
flagmust be astringand matches flags in themapidis an optionalstringtells resolver what to resolveuseDotNotationis an optionalbooleanindicates 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