Socket
Socket
Sign inDemoInstall

@smartlyio/safe-navigation

Package Overview
Dependencies
1
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @smartlyio/safe-navigation

typescript and null safe json object navigation


Version published
Weekly downloads
321
decreased by-48.64%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

safe-navigation

type(script) and null safe navigation in json objects

get .$

Returns the value or undefined if any value on the path to it is undefined

// yarn ts-node examples/getter.ts
import safe from '../index';
import * as assert from 'assert';

interface A {
  a?: { b?: string };
}
const o: A = { a: { b: 'x' } };
assert(safe(o).a.b.$ === 'x');

The optional chaining also takes into account union types.

// yarn ts-node examples/unions.ts
import safe from '../index';
import * as assert from 'assert';

type A = { a: number } | { b: string };
const o: A = { a: 1 };
assert(safe(o).a.$ === 1);

set value .$set

Returns a new object with the target set to value if the path to value exists

// yarn ts-node examples/set.ts
import safe from '../index';
import * as assert from 'assert';

interface A {
  a?: { b?: string };
}
const o: A = { a: { b: 'old' } };
const newValue: A = safe(o).a.b.$set('new');
assert(safe(newValue).a.b.$ === 'new');

map value .$map

Maps the value at end of the path

// yarn ts-node examples/map.ts
import safe from '../index';
import * as assert from 'assert';

interface A {
  a?: { b?: string };
}
const o: A = { a: { b: 'old' } };
const newValue: A = safe(o).a.b.$map((n: any) => n + ' to new');
assert(safe(newValue).a.b.$ === 'old to new');

map with promises .$pmap

Returns a new object with the target mapped using a promise returning map function

// yarn ts-node examples/pmap.ts
import safe from '../index';
import * as assert from 'assert';

interface A {
  a?: { b?: string };
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
(async function () {
  const o: A = { a: { b: 'x' } };
  const result = await safe(o).a.b.$pmap(async value => 'got ' + value);
  assert(safe(o).a.b.$ === 'x');
  assert(safe(result).a.b.$ === 'got x');
})();

Keywords

FAQs

Last updated on 29 Mar 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc