All files / src keyvalues.ts

100% Statements 98/98
100% Branches 34/34
100% Functions 12/12
100% Lines 98/98

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 6631x         1x 1x 1x 1x 1x 1x 1x                                                                 1x       28x 28x 28x         28x                                                   28x 28x   28x 28x                                                         28x 7x 7x                       28x 1x 1x                                                                                       28x 6x 6x 6x                                                                                     28x 7x 7x 7x                                                                                                                                     28x 14x 14x 14x 8x 8x 3x 9x   2x 1x 1x   1x 1x 14x                                                                                                                                 28x 58x   58x 53x 53x   4x 58x                                                                                                                           28x 12x 3x   3x 3x   9x 9x   9x   9x 12x                                                                                                                   28x 40x 11x   11x 40x 29x 29x   29x   29x 29x 40x                                                                                                               28x 7x   7x 6x 3x 3x 3x 3x 6x 6x   1x 7x                                                                                                       28x 6x   6x 5x 4x 4x   1x 1x   5x 5x   1x 6x 28x  
import { get as _get, has as _has, set as _set, unset as _unset } from "lodash";
import { DEFAULT_DIR_NAME, DEFAULT_FILE_NAME, JsonFileHelper } from "./internal/JsonFileHelper";
import type { KeyPath, Options, Types, valueTypes } from "./internal/types";
 
/** @internal */
const defaultOptions: Options = {
	atomicSave: true,
	dir: DEFAULT_DIR_NAME,
	fileName: DEFAULT_FILE_NAME,
	prettify: false,
	numSpaces: 2,
};
 
/**
 *
 * KeyValues is a class that provides a simple key-value storage system.
 * It allows you to set, get, check existence, and remove key-value pairs in a JSON file.
 * It supports nested keys and complex data types, and provides both asynchronous and synchronous methods
 *
 * It is designed to be used in Node.js applications
 * and can be easily configured to use a custom directory
 * and file name for storing key-value pairs.
 *
 * @author Heliomar Marques
 * @category Core
 * @example
 * // Create a new instance of KeyValues with custom options
 * const keyValues = new KeyValues({
 *   fileName: 'config.json',
 *   prettify: true
 * });
 *
 * // Set a key-value pair
 * await keyValues.set('color.name', 'sapphire');
 *
 * // Get the value at a specific key path
 * const value = await keyValues.get('color.name');
 *
 * // Check if a key path exists
 * const exists = await keyValues.has('color.name');
 *
 * // Remove a key-value pair
 * await keyValues.unset('color.name');
 */
export class KeyValues {
	/**
	 * @internal
	 */
	private options: Options = {
		...defaultOptions,
	};
 
	/**
	 * @internal
	 */
	private jsonHelper: JsonFileHelper;
 
	/**
	 * Sets the configuration for KeyValues Storage's. To reset
	 * to defaults, use [[reset|reset()]].
	 *```js
	 * Defaults:
	 *     {
	 *       atomicSave: true,
	 *       fileName: 'keyvalues.json',
	 *       numSpaces: 2,
	 *       prettify: false
	 *     }
	 *```
	 * @param options {@link Options} The custom configuration to use.
	 * @example
	 *
	 * Update the filename to `config.json` and prettify
	 * the output.
	 *```js
	 *     new KeyValues({
	 *       fileName: 'config.json',
	 *       prettify: true
	 *     });
	 * ```
	 */
	constructor(options?: Partial<Options>) {
		if (options) this.options = { ...this.options, ...options };
 
		this.jsonHelper = new JsonFileHelper(this.options);
	}
 
	/**
	 * Returns the path to the json file.
	 *
	 * In general, the json file is stored
	 * in then install location of your app's
	 * user data directory in a file called `keyvalues.json`.
	 * The default user data directory varies by system.
	 *
	 * - **macOS** - `~/Library/Application\ Support/<Your App>`
	 * - **Windows** - `%LOCALAPPDATA%/PROGRAMS/<Your App>`
	 * - **Linux** - Either `$XDG_CONFIG_HOME/<Your App>` or
	 * `~/.config/<Your App>`
	 *
	 * Although it is not recommended, you may change the name
	 * or location of the keyvalues file using
	 *
	 * new KeyValye({dir: 'newpath'})
	 *
	 * @returns The path to the keyvalues file.	 *
	 * @example
	 *
	 * Get the path to the keyvalues file.
	 *```js
	 *     keyValues.file();
	 *     // => c:/users/<userprofile>/appdata/local/programs/<AppName>/keyvalues.json
	 * ```
	 */
	file(): string {
		return this.jsonHelper.getJsonFilePath();
	}
 
	/**
	 * Resets the KeyValues Storage's configuration to defaults.
	 *
	 * @example
	 *
	 * Reset configuration to defaults.
	 *```js
	 *     keyValues.reset();
	 * ```
	 */
	reset(): void {
		this.options = { ...defaultOptions };
	}
 
	/**
	 * Checks if the given key path exists. For sync,
	 * use [[hasSync|hasSync()]].
	 *
	 * @param keyPath The key path to check.
	 * @returns A promise which resolves to `true` if the
	 * `keyPath` exists, else `false`.
	 * @example
	 *
	 * Check if the value at `color.name` exists.
	 *```js
	 *     // Given:
	 *     //
	 *     // {
	 *     //   "color": {
	 *     //     "name": "cerulean",
	 *     //     "code": {
	 *     //       "rgb": [0, 179, 230],
	 *     //       "hex": "#003BE6"
	 *     //     }
	 *     //   }
	 *     // }
	 *
	 *     const exists = await keyValues.has('color.name');
	 *     // => true
	 *```
	 * @example
	 *
	 * Check if the value at `color.hue` exists.
	 *```js
	 *     const h = 'hue';
	 *     const exists = await keyValues.has(['color', h]);
	 *     // => false
	 *```
	 *  @example
	 *
	 * Check if the value at `color.code.rgb[1]` exists.
	 *```js
	 *     const exists = await keyValues.has(color.code.rgb[1]);
	 *     // => true
	 * ```
	 */
	async has(keyPath: KeyPath): Promise<boolean> {
		const obj = await this.jsonHelper.loadKeyValues();
		return _has(obj, keyPath);
	}
 
	/**
	 * Checks if the given key path exists. For async,
	 * use [[hasSync|hasSync()]].
	 *
	 * @param keyPath The key path to check.
	 * @returns `true` if the `keyPath` exists, else `false`.
	 * @example
	 *
	 * Check if the value at `color.name` exists.
	 *```js
	 *     // Given:
	 *     //
	 *     // {
	 *     //   "color": {
	 *     //     "name": "cerulean",
	 *     //     "code": {
	 *     //       "rgb": [0, 179, 230],
	 *     //       "hex": "#003BE6"
	 *     //     }
	 *     //   }
	 *     // }
	 *
	 *     const exists = keyValues.hasSync('color.name');
	 *     // => true
	 *```
	 * @example
	 *
	 * Check if the value at `color.hue` exists.
	 *```js
	 *     const h = 'hue';
	 *     const exists = keyValues.hasSync(['color', h]);
	 *     // => false
	 *```
	 * @example
	 *
	 * Check if the value at `color.code.rgb[1]` exists.
	 *```js
	 *     const exists = keyValues.hasSync(color.code.rgb[1]);
	 *     // => true
	 * ```
	 */
	hasSync(keyPath: KeyPath): boolean {
		const obj = this.jsonHelper.loadKeyValuesSync();
		return _has(obj, keyPath);
	}
 
	/**
	 * Gets all key values. For sync, use
	 * [[getSync|getSync()]].
	 *
	 * @returns A promise which resolves with all key values.
	 * @example
	 *
	 * Gets all key values.
	 *```js
	 *     const obj = await get();
	 * ```
	 */
	async get<T extends valueTypes>(): Promise<T>;
 
	/**
	 * Gets the value at the given key path. For sync,
	 * use [[getSync|getSync()]].
	 *
	 * @param keyPath The key path of the property.
	 * @returns A promise which resolves with the value at the
	 * given key path.
	 * @example
	 *
	 * Get the value at `color.name`.
	 *```js
	 *     // Given:
	 *     {
	 *        "color": {
	 *          "name": "cerulean",
	 *          "code": {
	 *            "rgb": [0, 179, 230],
	 *            "hex": "#003BE6"
	 *          }
	 *        }
	 *     }
	 *
	 *     const value = await keyValues.get('color.name');
	 *     // => "cerulean"
	 *```
	 * @example
	 *
	 * Get the value at `color.code.hex`.
	 *```js
	 *     const hex = await keyValues.get('color.color.hex');
	 *     // => "#003BE6"
	 *```
	 * @example
	 *
	 * Get the value at `color.hue`.
	 *```js
	 *     const h = 'hue';
	 *     const value = await keyValues.get(['color', h]);
	 *     // => undefined
	 *```
	 * @example
	 *
	 * Get the value at `color.code.rgb[1]`.
	 *```js
	 *     const h = 'hue';
	 *     const value = await keyValues.get('color.code.rgb[1]');
	 *     // => 179
	 * ```
	 */
	async get<T extends valueTypes>(keyPath: KeyPath): Promise<T>;
 
	async get<T extends valueTypes>(keyPath?: KeyPath): Promise<T> {
		try {
			const obj = await this.jsonHelper.loadKeyValues<T>();
			if (keyPath) {
				return _get(obj, keyPath);
			}
			return obj;
		} catch (error) {
			// Add proper error handling
			if (error instanceof Error) {
				throw new Error(`Failed to get value: ${error.message}`);
			}
 
			throw new Error("Failed to get value: Unknown error");
		}
	}
 
	/**
	 * Gets all key values. For async, use [[get|get()]].
	 *
	 * @returns All key values.
	 * @example
	 *
	 * Gets all key values.
	 *```js
	 *     const obj = getSync();
	 * ```
	 */
	getSync<T extends valueTypes>(): T;
 
	/**
	 * Gets the value at the given key path. For async,
	 * use [[get|get()]].
	 *
	 * @param keyPath The key path of the property.
	 * @returns The value at the given key path.
	 * @example
	 *
	 * Get the value at `color.name`.
	 *```js
	 *     // Given:
	 *     {
	 *        "color": {
	 *          "name": "cerulean",
	 *          "code": {
	 *            "rgb": [0, 179, 230],
	 *            "hex": "#003BE6"
	 *          }
	 *        }
	 *     }
	 *
	 *     const value = keyValues.getSync('color.name');
	 *     // => "cerulean"
	 *```
	 * @example
	 *
	 * Get the value at `color.code.hex`.
	 *```js
	 *     const hex = keyValues.getSync('color.color.hex');
	 *     // => "#003BE6"
	 *```
	 * @example
	 *
	 * Get the value at `color.hue`.
	 *```js
	 *     const h = 'hue';
	 *     const value = keyValues.getSync(['color', h]);
	 *     // => undefined
	 *```
	 * @example
	 *
	 * Get the value at `color.code.rgb[1]`.
	 *```js
	 *     const h = 'hue';
	 *     const value = keyValues.getSync('color.code.rgb[1]');
	 *     // => 179
	 * ```
	 */
	getSync<T extends valueTypes>(keyPath: KeyPath): T;
 
	getSync<T extends valueTypes>(keyPath?: KeyPath): T {
		const obj = this.jsonHelper.loadKeyValuesSync<T>();
 
		if (keyPath) {
			return _get(obj, keyPath);
		}
 
		return obj;
	}
 
	/**
	 * Sets all key values. For sync, use [[setSync|setSync()]].
	 *
	 * @param obj The new key value.
	 * @returns A promise which resolves when the value have
	 * been set.
	 * @example
	 *
	 * Set all key values.
	 *```js
	 *     await keyValues.set({ aqpw: 'nice' });
	 * ```
	 */
	async set<T extends valueTypes>(obj: Types<T>): Promise<void>;
 
	/**
	 * Sets the value at the given key path. For sync,
	 * use [[setSync|setSync()]].
	 *
	 * @param keyPath The key path of the property.
	 * @param value The value to set.
	 * @returns A promise which resolves when the setting has
	 * been set.
	 * @example
	 *
	 * Change the value at `color.name` to `sapphire`.
	 *```js
	 *     // Given:
	 *     //
	 *     // {
	 *     //   "color": {
	 *     //     "name": "cerulean",
	 *     //     "code": {
	 *     //       "rgb": [0, 179, 230],
	 *     //       "hex": "#003BE6"
	 *     //     }
	 *     //   }
	 *     // }
	 *
	 *     await keyValues.set('color.name', 'sapphire');
	 *```
	 * @example
	 *
	 * Set the value of `color.hue` to `blue-ish`.
	 *```js
	 *     const h = 'hue';
	 *     await keyValues.set(['color', h], 'blue-ish);
	 *```
	 * @example
	 *
	 * Change the value of `color.code`.
	 *```js
	 *     await keyValues.set('color.code', {
	 *       rgb: [16, 31, 134],
	 *       hex: '#101F86'
	 *     });
	 * ```
	 */
	async set<T extends valueTypes>(keyPath: KeyPath, value: T): Promise<void>;
 
	async set<T extends valueTypes>(...args: [Types<T>] | [KeyPath, T]): Promise<void> {
		if (args.length === 1) {
			const [value] = args;
 
			return this.jsonHelper.saveKeyValues(value);
		}
 
		const [keyPath, value] = args;
		const obj = await this.jsonHelper.loadKeyValues<T>();
 
		_set(obj as object, keyPath, value);
 
		return this.jsonHelper.saveKeyValues(obj);
	}
 
	/**
	 * Sets all key values. For async, use [[set|set()]].
	 *
	 * @param obj The new key values.
	 * @example
	 *
	 * Set all key values.
	 *```js
	 *     keyValues.setSync({ aqpw: 'nice' });
	 * ```
	 */
	setSync<T extends valueTypes>(obj: Types<T>): void;
 
	/**
	 * Sets the value at the given key path. For async,
	 * use [[set|set()]].
	 *
	 * @param keyPath The key path of the property.
	 * @param value The value to set.
	 * @example
	 *
	 * Change the value at `color.name` to `sapphire`.
	 *```js
	 *     // Given:
	 *     //
	 *     // {
	 *     //   "color": {
	 *     //     "name": "cerulean",
	 *     //     "code": {
	 *     //       "rgb": [0, 179, 230],
	 *     //       "hex": "#003BE6"
	 *     //     }
	 *     //   }
	 *     // }
	 *
	 *     keyValues.setSync('color.name', 'sapphire');
	 *```
	 * @example
	 *
	 * Set the value of `color.hue` to `blue-ish`.
	 *```js
	 *     const h = 'hue';
	 *     keyValues.setSync(['color', h], 'blue-ish);
	 *```
	 * @example
	 *
	 * Change the value of `color.code`.
	 *```js
	 *     keyValues.setSync('color.code', {
	 *       rgb: [16, 31, 134],
	 *       hex: '#101F86'
	 *     });
	 * ```
	 */
	setSync<T extends valueTypes>(keyPath: KeyPath, value: T): void;
 
	setSync<T extends valueTypes>(...args: [Types<T>] | [KeyPath, T]): void {
		if (args.length === 1) {
			const [value] = args;
 
			this.jsonHelper.saveKeyValuesSync(value);
		} else {
			const [keyPath, value] = args;
			const obj = this.jsonHelper.loadKeyValuesSync<T>();
 
			_set(obj as object, keyPath, value);
 
			this.jsonHelper.saveKeyValuesSync(obj);
		}
	}
 
	/**
	 * Unsets all key values. For sync, use [unsetSync()].
	 *
	 * @returns A promise which resolves when the key values have
	 * been unset.
	 * @example
	 *
	 * Unsets all key values.
	 *```js
	 *     await keyValues.unset();
	 * ```
	 */
	async unset(): Promise<boolean>;
 
	/**
	 * Unsets the property at the given key path. For sync,
	 * use [[unsetSync|unsetSync()]].
	 *
	 * @param keyPath The key path of the property.
	 * @returns A promise which resolves when the setting has
	 * been unset.
	 * @example
	 *
	 * Unset the property `color.name`.
	 *```js
	 *     // Given:
	 *     //
	 *     // {
	 *     //   "color": {
	 *     //     "name": "cerulean",
	 *     //     "code": {
	 *     //       "rgb": [0, 179, 230],
	 *     //       "hex": "#003BE6"
	 *     //     }
	 *     //   }
	 *     // }
	 *
	 *     await keyValues.unset('color.name');
	 *
	 *     await keyValues.get('color.name');
	 *     // => undefined
	 *```
	 * @example
	 *
	 * Unset the property `color.code.rgba[1]`.
	 *```js
	 *     await keyValues.unset('color.code.rgba[1]');
	 *
	 *     await keyValues.get('color.code.rgb');
	 *     // => [0, null, 230]
	 * ```
	 */
	async unset(keyPath: KeyPath): Promise<boolean>;
 
	async unset(keyPath?: KeyPath): Promise<boolean> {
		const obj = await this.jsonHelper.loadKeyValues();
 
		if (JSON.stringify(obj) !== "{}") {
			if (keyPath && _unset(obj, keyPath)) {
				await this.jsonHelper.saveKeyValues(obj);
			} else {
				await this.jsonHelper.saveKeyValues({});
			}
			return true;
		}
 
		return false;
	}
 
	/**
	 * Unsets all key values. For async, use [unset()].
	 *
	 * @example
	 *
	 * Unsets all key values.
	 *```js
	 *     keyValues.unsetSync();
	 * ```
	 */
	unsetSync(): boolean;
 
	/**
	 * Unsets the property at the given key path. For async,
	 * use [[unset|unset()]].
	 *
	 * @param keyPath The key path of the property.
	 * @example
	 *
	 * Unset the property `color.name`.
	 *```js
	 *     // Given:
	 *     //
	 *     // {
	 *     //   "color": {
	 *     //     "name": "cerulean",
	 *     //     "code": {
	 *     //       "rgb": [0, 179, 230],
	 *     //       "hex": "#003BE6"
	 *     //     }
	 *     //   }
	 *     // }
	 *
	 *     keyValues.unsetSync('color.name');
	 *
	 *     keyValues.getSync('color.name');
	 *     // => undefined
	 *```
	 * @example
	 *
	 * Unset the property `color.code.rgba[1]`.
	 *```js
	 *     keyValues.unsetSync('color.code.rgba[1]');
	 *
	 *     keyValues.getSync('color.code.rgb');
	 *     // => [0, null, 230]
	 * ```
	 */
	unsetSync(keyPath: KeyPath): boolean;
 
	unsetSync(keyPath?: KeyPath): boolean {
		const obj = this.jsonHelper.loadKeyValuesSync();
 
		if (JSON.stringify(obj) !== "{}") {
			if (keyPath && _unset(obj, keyPath)) {
				this.jsonHelper.saveKeyValuesSync(obj);
			} else {
				// Unset all keyValues by saving empty object.
				this.jsonHelper.saveKeyValuesSync({});
			}
 
			return true;
		}
 
		return false;
	}
}