SkillAgentSearch skills...

Preconditions

Support for Guava like Precondition error checking in Node.js

Install / Use

/learn @corybill/Preconditions
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

Preconditions Library

view on npm npm module downloads Build Status Gitter

Support for Precondition error checking in Node.js

<p>Ensuring a fail fast development environment can help developers find bugs quicker and easier. Ensuring all invariants are true at an initial point of contact will help you ensure this fail fast environment. The Preconditions library will assist you in doing just that by immediately throwing an Error if any of your invariants fail. You can mix and match standard Guava API with convenience functions both with and without chaining.</p>

Version 2 Additions

<p>Version 2 adds a new entry point on the interface, 'errr'. The errr interface decorates the errr node module and helps to solve some important issues with Node, listed below. See https://www.npmjs.com/package/errr. This version also updates the module to Node 5 paradigms.</p>
  1. When templating / generating an error message, we must not string concat strings that are never used. Building an error message before it is needed, will take away cycles from more important tasks in the event queue. There are great performance gains to be found here if you are templating error messages.
  2. Appends Error stack traces together. If you append errors at each layer of your code, and only print the stack trace at the top most layer of your code, you will have stack traces that paint a much clearer picture when debugging. Allows you to get a more informative stack trace when using promise chains.
  3. Add debug params to stack traces to assist with bug resolution.

Install

<pre><code>npm install preconditions</code></pre>

Preconditions Interface

There are four functions that are exposed from the library.

  1. errr() - Verify a one value at a time while building an 'errr' object. You can append errors together and add debug params to the stack trace.
  2. singleton() - Verify one value at a time with a chainable preconditions interface.
  3. instance() - Create a testing suite passing in a single object. Run a single, or multiple tests on the passed in object. Shouldn't be used in production code.
  4. constructor() - Get the constructor function so you can extend the Preconditions library (see below for example). Shouldn't be used in production code.

Examples Using the Errr Interface (.errr())

You can use a static instance to verify one value at a time while using the errr module to build an errr. For more on the errr module see here https://github.com/corybill/Preconditions#errrdecorator and here https://github.com/corybill/errr#errr.

<pre> <code> var preconditions = require("preconditions").errr(); preconditions.shouldBeDefined(someObj.valueOne).test(); preconditions.shouldBeDefined(someObj.valueOne, "Custom error message.").test(); preconditions.shouldBeDefined(someObj.valueOne, "Error (%s:%s): Error Message.", [errType, errCode]).test(); preconditions.shouldBeDefined(someObj.valueOne, "Custom error message.").debug({param1: "someDebugParam"}).test(); preconditions.shouldBeDefined(someObj.valueOne, "Custom error message.").appendTo(someErrorObj).test(); preconditions.shouldBeDefined(someObj.valueTwo, "Error (%s:%s): Error Message.", [errType, errCode]); .debug({param1: "someDebugParam"}) .appendTo(someErrorObj) .test(); </code> </pre>

Examples Using In Promise Chain

Best practice for achieving fail fast concept when function must return promise;

<pre> <code> var preconditions = require("preconditions").errr(); new BlueBirdProm(function (resolve, reject { // THIS WILL THROW AND BE CAUGHT AT THE NEXT LEVEL OF THE CHAIN // NOTICE YOU DO NOT HAVE TO CALL REJECT BECAUSE WE ARE THROWING WITHIN A PROMISE. preconditions.shouldBeDefined(someObj.valueTwo, "Error (%s:%s): Error Message.", [errType, errCode]); .debug({param1: "someDebugParam"}) .set("reason", "Some Error").set("statusCode", 400) .appendTo(someErrorObj) .test(); // Can also short hand this call to .t(); return someAsynchFunc().then(function (result) { resolve(result); }).catch(function (err) { reject(err); }); }); </code> </pre>

Examples Using the Singleton Interface (.singleton())

You can use a static instance to verify one value at a time.

<pre> <code> var preconditions = require("preconditions").singleton(); preconditions.shouldBeDefined(someObj.valueOne) .shouldBeDefined(someObj.valueTwo, "Error (%s:%s): Error Message.", [errType, errCode]).test(); .shouldBeDefined(someObj.valueThree, "Custom error message."); </code> </pre>

Examples Using Instance Interface (.instance())

Should not be used in production code!

Setup Instance

<pre> <code> var preconditions = require("preconditions").instance(this); preconditions.shouldBeDefined("foo.deep.stringValue", "Custom error message.") .checkArguments("FOO" === "FOO"); </code> </pre>

Examples Using The Constructor (.constructor())

Should not be used in production code!

The Preconditions object itself is exposed so that you can extend the Preconditions class.

<pre> <code> let Constructor = preconditions.constructor(); let ChildClass = class extends Constructor { constructor(out) { super(out); } shouldBeFoo(value, message) { let msg = message || defaultMessage; if (value !== "FOO") { throw new Error(msg); } } }; new ChildClass(this).shouldBeDefined("foo.deep.stringValue", "Custom error message.") .shouldBeFoo("foo.deep.foo"); </code> </pre>

NPM Scripts

  1. npm run test - Run linter and unit tests.
  2. npm run ut - Use Maddox to Run Unit Tests.
  3. npm run perf - Use Maddox to Performance metrics.
  4. npm run uap - Use Maddox to Unit Tests and Performance metrics.
  5. npm run lint - Run linter.
  6. npm run docs - Rebuild public API Docs.

Missing API or Bugs

Please reach out to me (Cory Parrish) if you would like a new precondition added or if you think you have found a bug.

###Known Issues

  1. Release 1.0.2 has an npm install bug and has been deprecated! Please update!
  2. If you are using windows and are seeing npm install issues due to the '^' in the package.json, please update node to >= (v0.10.28).

Releases

  • 2.0.0
    • Adds errr interface which decorates errr node module
    • Allows templating in singleton interface.
    • Notes the poor performance in instance interface. Should not be used in production code.
    • Redesign of code.
    • Now uses maddox for unit testing.
    • Moves to Node 5 paradigms.
  • 1.0.8 - Removed 'underscore' and added 'lodash'.
    • Added a .jshintrc file and a more extensive linting process
    • Separated dependencies and dev-dependencies to reduce installation load (A big thanks to Esteban Ordano (eordano) for doing this work).
  • 1.0.7 - First official public release.

API

Classes

<dl> <dt><a href="#InstanceValidator">InstanceValidator</a></dt> <dd><p>Validate values in a nested object using a dot notation structure (e.g. .shouldBeString(&quot;Person.Address.Street.zip&quot;)) System will validate the the Person, Person.Address, and Person.Address.Street objects exist, and will validate that zip is a String.</p> <p>Use this interface if you want to utilize the following functionality:</p> <ol> <li>Nested object validation using a dot notation.</li> </ol> </dd> <dt><a href="#SingletonValidator">SingletonValidator</a></dt> <dd><p>Validate single value with a chainable interface. Use this interface if you want to utilize the following functionality:</p> <ol> <li>Error message templating.</li> <li>Only templates error message if validation fails which saves event queue cycles.</li> <li>Chain together precondition validations.</li> </ol> </dd> <dt><a href="#ErrrDecorator">ErrrDecorator</a></dt> <dd><p>Error Builder allows you to use optional functions to build an error object. The error can have appended stack traces and debug params to assist with debugging.</p> </dd> <dt><a href="#ErrrValidator">ErrrValidator</a></dt> <dd><p>Validate single value with a buildable interface on top of the errr node module. Use this interface if you want to utilize the following functionality:</p> <ol> <li>Error message templating.</li> <li>Only templates error message if ErrrValidator fails which saves event queue cycles.</li> <li>Gives ability to append Stack traces to an existing error.</li> <li>Gives ability to append debug params to stack trace.</li> </ol> </dd> <dt><a href="#Preconditions">Preconditions</a></dt> <dd><p>Preconditions entry point interface.</p> </dd> </dl>

<a name="InstanceValidator"></a>

InstanceValidator

Validate values in a nested object using a dot notation structure (e.g. .shouldBeString("Person.Address.Street.zip")) System will validate the the Person, Person.Address, and Person.Address.Street objects exist, and will validate that zip is a String.

Use this interface if you want to utilize the following functionality:

  1. Nested object validation using a dot notation.

Kind: global class

View on GitHub
GitHub Stars20
CategoryCustomer
Updated1y ago
Forks8

Languages

JavaScript

Security Score

60/100

Audited on Feb 6, 2025

No findings