0.1.3 • Published 4 years ago

optionally v0.1.3

Weekly downloads
2
License
MIT
Repository
github
Last release
4 years ago

optionally npm install optionally gzip size dependencies

Option parser with schema definition and descriptive errors:

const schema = {
  port: { default: 3000, type: Number },
  public: { default: "public", type: [String, Boolean] }
};

// All of these result in `{ port: 3000, public: "public" }`
optionally(schema);                   // Uses the defaults
optionally(schema, { port: "3000" }); // Cast to a number since it's possible
optionally(schema, {}, process.env);  // `.env` is `PORT=3000`

// Clear error messages:
optionally(schema, { port: "cow" });
// TypeError: The option `port` should be a number like `{ port: 3000 }` instead of the string "cow".

The arguments for each of the options, with all of them being optional:

keydescriptiontype
find()manually get the value from the paramsfunction
envname of the environment variable to usestring
argname of the argument to usestring
inheritfor subtrees, get the value from parentboolean, string
defaultvalue to use if none is providedany
parse()parse the previously found valuefunction
extendextend the default object with the valueboolean
validate()manually check that the value is correctfunction
typetype must match (or cast) to one of thesefunction, string, array
requiredvalue must be provided and foundboolean
enumit has to match exactly one of thesearray
optionsdefine the schema of the childrenobject

Internally it works in three steps, if you provide the main function then it will not perform the other actions:

  • find(): uses env > arg > inherit > default (in order) to attempt to get a value out of the arguments and environment.
  • clean(): uses extend, file and folder to expand the previously found value.
  • validate(): uses type, required, enum,

Helpers:

  • __root: "abcdef": if a single option is provided that is not an object, it will be converted into { abcdef: options }. Example: accept a port as a single argument { __root: "port" } + server(3000) = server({ port: 3000 }).
  • __mode: "strict": defines what to do with options that are not defined. "strict" will throw with keys that are not in the schema, "remove" will delete these extra keys and "flexible" will pass through any extra arguments.