Usage
Retrieving Values

The root node

The root node is the starting point and first node of the builder object. It is distinctive in how it behaves when interacting with the $use and $get properties.

When accessed using the $use property, the root node returns the register passed to the createBuilder function during initialization. Likewise, when accessed using the $get method, the root node returns the prefixes used to create the builder object. This behavior is unique to the root node and is not replicated in other nodes.

This guide elucidates the behavior of the $use and $get properties specifically on the root node.

const register = {
  foo: {
    baz: (id: number) => `/bazaar/${id}`,
    bar: 10,
  },
};
 
const builder = createBuilder(register, { prefix: ["root", "node"]});

Retrieving values

Accessing the $use property on the root node returns the register in its entirety, thereby enabling access to its values. This behavior is distinct from that of other nodes, which generate a key derived from the nested keys within the register, rather than providing direct access to the register and its sub-keys.

Because of the dual-purpose nature of the $use property, it is important to distinguish between the $use property that returns the value and the $use method that returns the key. The rule of thumb is to remember that the $use property that returns the value is always situated closest to the root node. While the $use method that returns the key is always situated at the end of the chain.

The following code snippet demonstrates how to retrieve register values:

builder.$use; // { foo: { baz: [Function: baz], bar: 10 } }
 
// Accessing a nested function value
builder.$use.foo.baz(12); // "/bazaar/12"
 
// Accessing a nested primitive value
builder.$use.foo.bar; // 10

Builder prefix

The root node is the only node that does not have a key. This is because its name resides outside the hierarchy of the builder object. However, it can be assigned one by passing an array of strings as a second argument to the createBuilder function. This array not only serves as the key for the root node but also as a prefix for other nodes.

To retrieve this prefix, the $get method is used. The $get method returns the prefixes that were used to create the builder object. If no prefix has been set, this method will return an empty array, reflecting the absence of associated prefixes.

The following code snippet demonstrates how to retrieve the root key:

builder.$get(); // ["root", "node"]