项目作者: UnderNotic

项目描述 :
Simple and natural nested property accessor. For node and browser.
高级语言: JavaScript
项目地址: git://github.com/UnderNotic/guardy.git
创建时间: 2018-01-24T17:58:21Z
项目社区:https://github.com/UnderNotic/guardy

开源协议:MIT License

下载


" class="reference-link">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.

  1. npm install guardy --save

Using yarn

  1. yarn add guardy --save

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

  1. <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.

  1. import { guardy } from "guardy";
  2. var nestedProp = guardy(myObj).I.can.safely.access.any.property;

With defined fallback value

  1. import { guardyFb } from "guardy";
  2. 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.

  1. const mapStateToProps = ({ NestedReducerState }) => (
  2. {
  3. var nestedStateObject = guardy(NestedReducerState).a.nested.object;
  4. var nestedStateString = guardyWithFallback(NestedReducerState, "defaultString").a.nested.string.__value__;
  5. return {
  6. nestedStateObject,
  7. nestedStateString
  8. }
  9. }
  10. );

Compatibility

Licensing

The code in this project is licensed under MIT license.