-
Notifications
You must be signed in to change notification settings - Fork 86
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: move pickContext to its own module
- Loading branch information
1 parent
941523c
commit 1036b96
Showing
2 changed files
with
44 additions
and
39 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
var forEach = require('./forEach'); | ||
|
||
/** | ||
* Pick keys from the context object | ||
* @method pickContext | ||
* @param {Object} context - context object | ||
* @param {Function|Array|String} picker - key, array of keys or | ||
* function that return keys to be extracted from context. | ||
* @param {String} method - method name, GET or POST | ||
*/ | ||
function pickContext(context, picker, method) { | ||
if (!picker || !picker[method]) { | ||
return context; | ||
} | ||
|
||
var p = picker[method]; | ||
var result = {}; | ||
|
||
if (typeof p === 'string') { | ||
result[p] = context[p]; | ||
} else if (Array.isArray(p)) { | ||
p.forEach(function (key) { | ||
result[key] = context[key]; | ||
}); | ||
} else if (typeof p === 'function') { | ||
forEach(context, function (value, key) { | ||
if (p(value, key, context)) { | ||
result[key] = context[key]; | ||
} | ||
}); | ||
} else { | ||
throw new TypeError( | ||
'picker must be an string, an array, or a function.' | ||
); | ||
} | ||
|
||
return result; | ||
} | ||
|
||
module.exports = pickContext; |