0.7.0 ā€¢ Published 1 year ago

confignition v0.7.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

This TypeScript library provides a simple and efficient way to parse different types of config files, including JSON, YAML, INI, .env, and TOML. Additionally, it supports retrieving files stored on AWS S3 or Azure Blob.


Supported File Types

The library current supports the following file types:

  • JSON
  • YAML
  • INI
  • .env
  • TOML

Installation

To install the package you can use npm or yarn:

npm install confignition

or

yarn add confignition

Usage

To use this library, first import it (supports both ES5 and ES6+):

const { parse, getConfig } = require('confignition');

or

import { parse, getConfig } from 'confignition';

Examples

  • For the following example config:

    [server]
    host = "localhost"
    port = 5000
    
    [database]
    url = "postgres://username:password@localhost/mydatabase"

[database.options] https = true auth = "basic"

- Parse a local file

```js
const config = parse('src/configs/config.toml');

/**
 {
  port: 5000,
  host: 'localhost',
 }
 */

NOTE: you can also specify the file type if the extension does not match the file format

const config = parse('src/configs/config.txt', { type: 'toml' });
  • Retrieve the parsed configurationn object

    const config = getConfig();
    
    /**
     {
      port: 5000,
      host: 'localhost',
     }
     */
  • Update configuration file

    const updatedConfig = update({ newConfig: 'updated' });

Parse configuration

To parse the configuration, you can use the parse function. The function accepts 2 arguments:

  • The file path - relative to the root directory of the project
  • An object to specify options (optional)
// The type is inferred
import { parse } from 'confignition';
const config = parse('src/configs/.env');

// or

// The type must be specified because the file extension does not match the format type
const config = parse('src/config/config.txt', { type: 'dotenv' });

Custom parsing

In additional to the parsing algorithms provided, you can write your own. Especially useful if the config format is not currently supported or requires extra steps.

import { customParse } from 'confignition';

const config = customParse(
  'src/config/config.cfg',
  (content) => {
    let conf;
    // ...parsing logic
    return conf;
  },
  { type: 'cfg' } // the type is required as it is not inferred.
);

Dynamically update config file

To update the existing configuration or create a new file and subscribe to it, you can use the update function. The function accepts 2 arguments:

  • The new configuration object or a callback similar to React's useState hook.
// Override configuration
const updatedConfig = update({ override: true });

// or

// Add additional fields to existing configuration
const updatedConfig = update((prev) => ({
  ...prev,
  additionalSection: {
    updatedConfig: true,
  },
}));

// Create a new configuration file and subscribe to it
const updateConfig = update(
  { newConfig: true, version: '0.2.0' },
  {
    createNewFile: true,
    newFileOptions: {
      path: 'src/configs/newConfig.json', // if the file already exists, it will override its content.
      type: 'json', // optional. Type will be inferred from the file name
    },
  }
);

Remote Configurations (STILL IN PROGRESS)

Currently, the library supports retrieving files from AWS S3 Buckets and Azure Blob Storages. Pass the remote file name as the file path and add the configurations needed to access the remote storage.

  • AWS:
const config = parse('config_on_aws', {
  type: 'json',
  fromCloud: true,
  cloudConfig: {
    aws: {
      s3Bucket: 'my-bucket',
      awsConfig: {
        /* aws configs */
      },
      // refer to the AWS SDK Docs: https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/interfaces/s3clientconfig.html
    },
  },
});
  • Azure:
const config = parse('config_on_azure', {
  type: 'ini',
  fromCloud: true,
  cloudConfig: {
    azure: {
      connectionString: 'my-bucket',
      containerName: 'my-container',
      // refer to the Azure SDK Docs: https://learn.microsoft.com/en-us/javascript/api/@azure/storage-blob/blobserviceclient?view=azure-node-latest#@azure-storage-blob-blobserviceclient-constructor-1
    },
  },
});

Hot Reload

The library supports hot reloading of the config file. Set the hotReload to true

const config = parse('../config.toml', {
  hotReload: true,
  hotReloadInterval: 2000, // in ms. Default: 1000ms
});

NOTE: Hot reload only works for local files. Changes to remote files will not trigger an update.


Express Integration

A middleware is available for integration with the Express framework. The middleware injects the existing configuration or parsed a new one (if the filepath is specified) into the request object.

import * as express from 'express';
import { expressConfignition } from 'confignition';
const app = express();

app.use(expressConfignition('src/configs/config.ini'));

app.get('/', (req, res) => {
  const { config, params } = req;
  // ...
});

or

import * as express from 'express';
import { parse, expressConfignition } from 'confignition';

parse('src/configs/config.yaml');

const app = express();

app.use(expressConfignition());

app.get('/', (req, res) => {
  const { config, params } = req;
  // ...
});

Encryption (Coming Soon)

In a future release, the library will support encryption of the config files (or part of them). This will allow you to store sensitive information such as API keys, passwords, and tokens securely.


Author

šŸ‘¤ Andrea Pallotta

For inquiries, suggestions, and criticisms, you can reach me via:


šŸ¤ Contributing

Contributions, issues and feature requests are welcome!Feel free to check issues page.

If you have your own template repository, I suggest to clone this tool and change the source repository!


Show your support

Give a ā­ļø if you found this tool useful or interesting!


šŸ“ License

This project is MIT licensed.

0.7.0

1 year ago

0.6.0

1 year ago

0.5.0

1 year ago

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago