update

Updates an existing global variable by deeply merging new properties from the updates object into the current value associated with the specified key.

Purpose: This method updates the value of an existing global variable in the Node.js global object by merging new properties into its current value. The update method allows you to perform a deep merge of the updates object into the current value associated with the specified key. This is useful for modifying complex objects without losing existing properties.

Parameters:

  • key (string): The name of the global variable that will be updated. This should be a unique string identifying the variable and must already exist in the global object.

  • updates (object): An object containing properties that will be merged into the current value of the global variable. The merge operation is recursive, meaning that nested objects will be merged deeply. If the current value is not an object, an error will be thrown.

Usage Example:

const globalManager = require('global-manager');

// Set an initial global variable
globalManager.set('config', { settings: { theme: 'dark', version: 1 } });

// Update the global variable with new properties
globalManager.update('config', { settings: { version: 2 }, newFeature: true });

// Retrieve and print the updated global variable
const updatedConfig = globalManager.get('config');
console.log(updatedConfig); 
// Output: { settings: { theme: 'dark', version: 2 }, newFeature: true }

Detailed Explanation: The update method merges the properties of the updates object into the existing value of the specified key. If the key does not exist, an error is thrown. If the current value of the key is not an object, an error is also thrown. This method is particularly useful for incrementally updating complex configurations or settings stored in global variables.

Notes:

  • Key Existence: Ensure the global variable specified by key already exists before calling update. If it does not, an error will be thrown.

  • Object Validation: The method assumes the current value associated with the key is an object. If it is not an object, an error will be thrown. Ensure the global variable is initialized with an object before using update to avoid runtime errors.

  • Deep Merge: The merge operation performed by this method is deep, so nested objects in updates will be merged recursively into the current value. Be mindful of potential unintended overwrites of deeply nested properties.

Last updated