js-optchain
This package adds schema-based optional chaining to javascript. Simply wrap the object with the oc
and define your default schema. This will create an object containing all fields specified in the schema with the existing values or default ones from the schema if the data is undefined. The optional chain is recursively generated so schemas can be multi-level. See Usage for examples.
Installation
NPM:
npm install js-optchain
Yarn:
yarn add js-optchain
Importing:
With import:
;
With require:
const oc = default;
Usage
/** * Wrap an object with optional properties which should have default values if undefined. * * To use partials, set the element in the schema to `{}` * * Partials are enabled by default. If partials are not enabled, the output will strictly match the schema shape. * * @param * @param * @param */const ocObj = ;
- The first argument is the object you want to explore that may or may not be
undefined
. - The second argument is the schema of its optional chain with default values.
- There is an optional third argument that defaults to true and allows partial schemas (see handler/ocBody 6 below for an example)
- The returned result is an object that will match the schema and have default values if the found values are
undefined
. This can include nested objects, see examples below.
Examples
Below are a series of examples that match the following. To view an example, see the handler
, oc()
and console.log
for each number to see what the expected inputs and outputs are.
ocBody1
: Passing an undefined object into theoc
wrapper (object is undefined)ocBody2
: Passing an empty object into theoc
wrapper (object has none of the schema properties)ocBody3
: Passing a partial object into theoc
wrapper (object only has some of the schema properties)ocBody4
: Passing a complete object into theoc
wrapper (object has all the schema properties)ocBody5
: Passing a nested object into theoc
wrapper (schema contains multiple layers)ocEvent5
: Passing a more complex object into theoc
wrapperocEvent6
: Passing an object into theoc
wrapper with partialsocEvent6NoPartials
: Passing an object into theoc
wrapper with partials disabled
Therefore, all of these inputs are valid:
// import oc from "js-optchain";const oc = default; const handler1 = event: {}; const handler2 = event: body: {} ; const handler3 = event: body: username: "jeff" ; const handler4 = event: body: username: "jeff" password: "password" ; const handler5 = event: body: user: username: "jeff" ; const handler6 = event: body: user: username: "jeff" password: "password" ; const ocBody1 = ;const ocBody2 = ;const ocBody3 = ;const ocBody4 = ;const ocBody5 = ;const ocEvent5 = ;const ocEvent6 = ;const ocEvent6NoPartials = ; console;console;console;console;console;console;console;console;