Skip to content

Simple and natural nested property accessor. For node and browser.

License

Notifications You must be signed in to change notification settings

UnderNotic/guardy

Repository files navigation

portfolio_view

CircleCI Coverage Status BCH compliance License: MIT dependencies Status

NPM

Simple and natural nested property accessor.
Protect yourself from "Cannot read property 'x' of undefined" runtime exception.

Installing

Package is available in npm. It's in umd format so it will work correctly with all popular bundlers(webpack) and also nodejs.

npm install guardy --save

Using yarn

yarn add guardy --save

For direct usage without bundler, use iife format and import file directly:

<script src="dist/guardy-iife.min.js"></script>

Usage

Wrap object with guardy and then access with no stress any property at any nested level. If not defined it will fallback to empty object {} instead of throwing "Cannot read property 'x' of undefined" runtime exception.

import { guardy } from "guardy";

var nestedProp = guardy(myObj).I.can.safely.access.any.property;

With defined fallback value

import { guardyFb } from "guardy";

var nestedProp = guardyFb(myObj, "myFallBackStringOrAnyType").I.can.safely.access.any.property.__value__;

Guardy can be successfully used together with redux when trying to access not yet initialized state properties by providing safe fallback values.

const mapStateToProps = ({ NestedReducerState }) => (
    {
       var nestedStateObject = guardy(NestedReducerState).a.nested.object;
       var nestedStateString = guardyWithFallback(NestedReducerState, "defaultString").a.nested.string.__value__;

       return {
           nestedStateObject,
           nestedStateString
       }
    }
);

Compatibility

Licensing

The code in this project is licensed under MIT license.

About

Simple and natural nested property accessor. For node and browser.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published