UNPKG

1.53 kBJavaScriptView Raw
1var assert = require('assert');
2
3module.exports = function parseAndValidateOptions(params, schema, displayName) {
4 // ensure required parameters are passed in
5 Object.keys(schema)
6 .filter(function(key) {
7 if (schema[key].isRequired instanceof Function) {
8 return schema[key].isRequired();
9 }
10 return schema[key].isRequired;
11 })
12 .forEach(function(key) {
13 assert(params.hasOwnProperty(key),
14 format("Missing required parameter '" + key + "'")
15 );
16 })
17 ;
18
19 return Object.keys(params).reduce(function(hsh, key) {
20 var spec = schema[key];
21 var value = params[key];
22 var validationError;
23
24 assert(schema.hasOwnProperty(key),
25 format("Unrecognized option '" + key + "'")
26 );
27
28 if (spec.validate) {
29 validationError = spec.validate(value);
30
31 assert(!validationError, format(validationError));
32 }
33
34 if (spec.type) {
35 assert(typeof value === spec.type,
36 format("Option '" + key + "' must be of type '" + spec.type + "' not '" + typeof value + "'.")
37 );
38 }
39
40 if (spec.default && (value === undefined || value === null)) {
41 hsh[key] = spec.default;
42 }
43 else {
44 hsh[key] = value;
45 }
46
47 return hsh;
48 }, getDefaults());
49
50 function getDefaults() {
51 return Object.keys(schema).reduce(function(hsh, key) {
52 if (schema[key].default) {
53 hsh[key] = schema[key].default;
54 }
55
56 return hsh;
57 }, {});
58 }
59
60 function format(message) {
61 return displayName + ": " + message;
62 }
63};
\No newline at end of file