npmextra/readme.md

312 lines
11 KiB
Markdown
Raw Normal View History

2023-08-03 17:22:34 +00:00
# @push.rocks/npmextra
2024-06-12 18:21:51 +00:00
A utility to enhance npm with additional configuration, tool management capabilities, and a key-value store for project setups.
2024-04-14 01:45:31 +00:00
## Install
To install `@push.rocks/npmextra`, use the following npm command:
```bash
npm install @push.rocks/npmextra --save
```
This package is available on [npm](https://www.npmjs.com/package/@push.rocks/npmextra) and can be installed into your project as a dependency to enhance npm with additional configuration and tool management capabilities.
2021-01-27 21:10:31 +00:00
## Usage
2024-06-12 18:10:19 +00:00
`@push.rocks/npmextra` is designed to supplement npm functionalities with enhanced configuration and tool management. It facilitates the management of project configurations and tool setups in a consolidated manner, enabling a smoother workflow and maintenance process. Below are detailed use cases and examples implemented with ESM syntax and TypeScript.
2024-04-14 01:45:31 +00:00
### Initial Setup and Configuration
2024-06-12 18:18:27 +00:00
To start using `npmextra` in your project, first include it with an import statement:
2021-01-27 21:10:31 +00:00
2024-04-14 01:45:31 +00:00
```typescript
import { Npmextra } from '@push.rocks/npmextra';
```
Instantiate the `Npmextra` class optionally with a custom path to your project's working directory. If no path is provided, the current working directory (`process.cwd()`) is used.
2021-01-27 21:10:31 +00:00
2024-04-14 01:45:31 +00:00
```typescript
const npmExtraInstance = new Npmextra('/path/to/your/project');
```
2021-01-27 21:10:31 +00:00
2024-04-14 01:45:31 +00:00
### Managing Tool Configurations with `npmextra.json`
2024-06-12 18:18:27 +00:00
`@push.rocks/npmextra` excels in unifying tool configurations through a single `npmextra.json` file. Instead of scattering configurations across multiple files, `npmextra` enables you to define tool-specific settings within this centralized configuration file, which can then be accessed programmatically.
2021-01-27 21:10:31 +00:00
2024-04-14 01:45:31 +00:00
#### Creating and Utilizing `npmextra.json`
Create a `npmextra.json` in your project root with the following structure:
2021-01-27 21:10:31 +00:00
```json
{
2024-04-14 01:45:31 +00:00
"toolname": {
"setting1": "value1",
"setting2": "value2"
2021-01-27 21:10:31 +00:00
}
}
```
2024-04-14 01:45:31 +00:00
For example, to configure a hypothetical tool named `toolname`, define its settings as shown above.
#### Accessing Configuration in Your Project
With the configuration defined, you can easily access these settings in your TypeScript code as follows:
2021-01-27 21:10:31 +00:00
```typescript
2024-06-12 18:10:19 +00:00
// Import the npmextra module
2024-04-14 01:45:31 +00:00
import { Npmextra } from '@push.rocks/npmextra';
2024-06-12 18:10:19 +00:00
// Create an instance pointing at the current directory
2024-04-14 01:45:31 +00:00
const npmExtraInstance = new Npmextra();
2021-01-27 21:10:31 +00:00
2024-06-12 18:10:19 +00:00
// Retrieve the configuration for 'toolname', merging defaults with any found in npmextra.json
2024-06-12 18:18:27 +00:00
const toolConfig = npmExtraInstance.dataFor<{ setting1: string, setting2: string }>('toolname', {
setting1: 'defaultValue1',
setting2: 'defaultValue2'
2021-01-27 21:10:31 +00:00
});
2024-04-14 01:45:31 +00:00
// toolConfig now contains the merged settings from npmextra.json and provided defaults
console.log(toolConfig);
2021-01-27 21:10:31 +00:00
```
2024-04-14 01:45:31 +00:00
### Key-Value Store Management
`@push.rocks/npmextra` also includes a Key-Value Store (KeyValueStore) functionality enabling persistent storage of key-value pairs between script executions.
#### Setting Up KeyValueStore
To utilize the KeyValueStore, create an instance specifying its scope (e.g., 'userHomeDir') and a unique identity for your application or tool:
```typescript
import { KeyValueStore } from '@push.rocks/npmextra';
2024-06-12 18:18:27 +00:00
const kvStore = new KeyValueStore<'userHomeDir'>({
typeArg: 'userHomeDir',
identityArg: 'myUniqueAppName'
});
2024-04-14 01:45:31 +00:00
```
You can then use the `writeKey`, `readKey`, `writeAll`, and `readAll` methods to manage your store respectively.
#### Example: Storing and Retrieving Data
```typescript
// Write a single key-value pair
await kvStore.writeKey('username', 'johnDoe');
// Read a single key
const username = await kvStore.readKey('username');
console.log(username); // Outputs: johnDoe
// Write multiple key-value pairs
await kvStore.writeAll({
email: 'john@example.com',
isAdmin: true
});
// Read all key-value pairs
const allData = await kvStore.readAll();
console.log(allData); // Outputs the entire store's contents
```
2024-06-12 18:18:27 +00:00
### Advanced Key-Value Store Management
2024-06-12 18:10:19 +00:00
2024-06-12 18:18:27 +00:00
In addition to basic read/write operations, `npmextra`s `KeyValueStore` supports advanced scenarios like mandatory keys and custom file paths.
2024-06-12 18:10:19 +00:00
#### Example: Mandatory Keys and Custom Paths
2024-06-12 18:18:27 +00:00
Consider a scenario where your application requires specific keys to be present in the KeyValueStore. You can define mandatory keys and use a custom path for your store like this:
2024-06-12 18:10:19 +00:00
```typescript
import { KeyValueStore } from '@push.rocks/npmextra';
interface CustomData {
key1: string;
key2: number;
key3?: boolean;
}
const kvStore = new KeyValueStore<CustomData>({
typeArg: 'custom',
identityArg: 'customApp',
customPath: '/custom/path/to/store.json',
mandatoryKeys: ['key1', 'key2']
});
// Ensure all mandatory keys are present
const missingKeys = await kvStore.getMissingMandatoryKeys();
if (missingKeys.length) {
console.log(`Missing mandatory keys: ${missingKeys.join(', ')}`);
}
// Use the KeyValueStore
await kvStore.writeKey('key1', 'value1');
await kvStore.writeKey('key2', 123);
const key1Value = await kvStore.readKey('key1');
const allData = await kvStore.readAll();
console.log(key1Value); // Outputs: value1
console.log(allData); // Outputs: { key1: 'value1', key2: 123 }
```
### Combining AppData and KeyValueStore
2024-06-12 18:18:27 +00:00
The `AppData` class extends the functionality of `KeyValueStore` by integrating environmental variables, specifying additional configurations, and providing a more structured approach to data management.
2024-06-12 18:10:19 +00:00
#### Example: AppData Usage
```typescript
import { AppData } from '@push.rocks/npmextra';
interface AppSettings {
settingA: string;
settingB: number;
nestedSetting: {
innerSetting: boolean;
}
}
const appDataInstance = await AppData.createAndInit<AppSettings>({
dirPath: '/custom/path/to/appdata',
requiredKeys: ['settingA', 'settingB'],
envMapping: {
settingA: 'MY_ENV_A',
settingB: 'hard:42',
nestedSetting: {
innerSetting: 'MY_ENV_INNER'
}
}
});
const appDataKvStore = await appDataInstance.getKvStore();
// Writing values
await appDataKvStore.writeKey('settingA', 'exampleValue');
await appDataKvStore.writeKey('settingB', 100);
await appDataKvStore.writeKey('nestedSetting', { innerSetting: true });
// Reading values
const settingA = await appDataKvStore.readKey('settingA');
const allSettings = await appDataKvStore.readAll();
console.log(settingA); // Outputs: 'exampleValue'
console.log(allSettings); // Outputs: { settingA: 'exampleValue', settingB: 100, nestedSetting: { innerSetting: true } }
```
### Error Handling and Debugging
2024-06-12 18:18:27 +00:00
Proper error handling ensures your integrations with `npmextra` are robust and stable. Below are some strategies for error handling and debugging potential issues.
2024-06-12 18:10:19 +00:00
#### Example: Error Handling in KeyValueStore
```typescript
import { KeyValueStore } from '@push.rocks/npmextra';
const kvStore = new KeyValueStore('userHomeDir', 'errorHandlingApp');
try {
await kvStore.writeKey('importantKey', 'importantValue');
const value = await kvStore.readKey('importantKey');
console.log(value); // Outputs: importantValue
} catch (error) {
console.error('Error managing key-value store:', error);
}
```
#### Debugging Configuration Issues in `npmextra.json`
To debug configuration issues, you can utilize conditional logging and checks:
```typescript
import { Npmextra } from '@push.rocks/npmextra';
const npmExtraInstance = new Npmextra();
const toolConfig = npmExtraInstance.dataFor('toolname', {
configKey1: 'defaultValue1',
configKey2: 'defaultValue2'
});
if (!toolConfig.configKey1) {
console.error('configKey1 is missing in npmextra.json');
}
console.log(toolConfig);
```
### Integration Tests
2024-06-12 18:18:27 +00:00
2024-06-12 18:10:19 +00:00
Writing tests ensures that your integration with `npmextra` works as expected. Below are examples of integration tests for both `Npmextra` and `KeyValueStore`.
#### Example: Testing `Npmextra` Class
```typescript
import { expect, tap } from '@push.rocks/tapbundle';
import { Npmextra } from '@push.rocks/npmextra';
let npmExtraInstance: Npmextra;
tap.test('should create an instance of Npmextra', async () => {
npmExtraInstance = new Npmextra();
expect(npmExtraInstance).toBeInstanceOf(Npmextra);
});
tap.test('should load configuration from npmextra.json', async () => {
const config = npmExtraInstance.dataFor('toolname', {
defaultKey1: 'defaultValue1',
});
expect(config).toHaveProperty('defaultKey1');
});
tap.start();
```
#### Example: Testing `KeyValueStore` Class
```typescript
import { expect, tap } from '@push.rocks/tapbundle';
import { KeyValueStore } from '@push.rocks/npmextra';
let kvStore: KeyValueStore<{ key1: string, key2: number }>;
tap.test('should create a KeyValueStore instance', async () => {
2024-06-12 18:18:27 +00:00
kvStore = new KeyValueStore({
typeArg: 'userHomeDir',
identityArg: 'testApp'
});
2024-06-12 18:10:19 +00:00
expect(kvStore).toBeInstanceOf(KeyValueStore);
});
tap.test('should write and read back a value', async () => {
await kvStore.writeKey('key1', 'value1');
const result = await kvStore.readKey('key1');
expect(result).toEqual('value1');
});
tap.test('should write and read back multiple values', async () => {
await kvStore.writeAll({ key1: 'updatedValue1', key2: 2 });
const result = await kvStore.readAll();
expect(result).toEqual({ key1: 'updatedValue1', key2: 2 });
});
tap.start();
```
### Summary
2024-06-12 18:18:27 +00:00
By centralizing configuration management and offering a versatile key-value store, `@push.rocks/npmextra` significantly simplifies the setup and management of tools and settings in modern JavaScript and TypeScript projects. Whether you're managing project-wide configurations or need persistent storage for key-value pairs, `npmextra` provides an efficient and streamlined solution. Leveraging these robust features will ensure your project is well-configured and maintainable.
2024-04-14 01:45:31 +00:00
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
2021-01-27 21:10:31 +00:00
2024-04-14 01:45:31 +00:00
### Trademarks
2021-01-27 21:10:31 +00:00
2024-04-14 01:45:31 +00:00
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
2021-01-27 21:10:31 +00:00
2024-04-14 01:45:31 +00:00
### Company Information
2021-01-27 21:10:31 +00:00
2024-04-14 01:45:31 +00:00
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
2021-01-27 21:10:31 +00:00
2024-04-14 01:45:31 +00:00
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
2021-01-27 21:10:31 +00:00
2024-04-14 01:45:31 +00:00
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.