### Complete Application Configuration Example (JavaScript) Source: https://context7.com/meltwater/aws-configuration-fetcher/llms.txt Demonstrates a real-world serverless application setup combining multiple configuration sources (SSM, Secrets Manager, local) with adapters, caching, and error handling. It shows how to load and process various types of configuration data. ```javascript import { createConfigurationRepository, ConfigurationRequest, ConfigurationRequestTypes, createSsmStringConfigurationRequest, createSecretStringConfigurationRequest } from '@meltwater/aws-configuration-fetcher' import cacheManager from 'cache-manager' import pino from 'pino' // Setup logger const log = pino({ level: 'info' }) // Configure cache with Redis store (optional) const cache = cacheManager.caching({ store: 'memory', max: 50, ttl: 120 // 2 minutes }) // Create repository with custom options const configRepo = createConfigurationRepository({ cache, cacheKey: 'app-configuration', log }) // Define application configuration async function loadAppConfiguration() { try { const config = await configRepo.getConfiguration([ // Database configuration createSsmStringConfigurationRequest('dbHost', '/prod/db/host'), new ConfigurationRequest({ key: '/prod/db/port', propertyName: 'dbPort', type: ConfigurationRequestTypes.ssm, adapter: (value) => parseInt(value, 10) }), createSecretStringConfigurationRequest('dbPassword', 'prod/db/password'), // JSON configuration from Secrets Manager new ConfigurationRequest({ key: 'prod/oauth/credentials', propertyName: 'oauthConfig', type: ConfigurationRequestTypes.secret, adapter: (value) => { const parsed = JSON.parse(value) if (!parsed.clientId || !parsed.clientSecret) { throw new Error('Invalid OAuth configuration') } return parsed } }), // Feature flags from SSM with boolean conversion new ConfigurationRequest({ key: '/prod/features/new-ui', propertyName: 'enableNewUI', type: ConfigurationRequestTypes.ssm, adapter: (value) => value.toLowerCase() === 'true' }), // Local fallback values new ConfigurationRequest({ key: 'https://api.fallback.com', propertyName: 'fallbackApiUrl', type: ConfigurationRequestTypes.local }) ]) return config } catch (error) { log.error({ error }, 'Failed to load configuration') throw error } } // Usage in Lambda handler export const handler = async (event) => { const config = await loadAppConfiguration() // Connect to database const dbConnection = `postgresql://${config.dbHost}:${config.dbPort}` // Use OAuth credentials console.log(`OAuth Client ID: ${config.oauthConfig.clientId}`) // Check feature flag if (config.enableNewUI) { // Render new UI } return { statusCode: 200, body: 'Success' } } ``` -------------------------------- ### Project Setup and Development Environment Source: https://github.com/meltwater/aws-configuration-fetcher/blob/master/README.md Steps for setting up the development environment for the aws-configuration-fetcher project, including cloning the repository, installing Node.js and dependencies, and running development servers. ```bash $ git clone https://github.com/meltwater/aws-configuration-fetcher.git serverless-nodejs $ cd serverless-nodejs $ nvm install $ yarn install ``` ```bash $ yarn run offline $ yarn run test:watch ``` ```bash $ yarn run ``` -------------------------------- ### Register Example in Index Source: https://github.com/meltwater/aws-configuration-fetcher/blob/master/examples/README.md Illustrates how to register a newly created example function within the main examples index file to make it available for execution. ```javascript import queryApi from './query-api' export const examples = { queryApi } ``` -------------------------------- ### Create New Example Function Source: https://github.com/meltwater/aws-configuration-fetcher/blob/master/examples/README.md Shows the pattern for defining a new example module. The function accepts configuration options and arguments, performs logic, and returns data to be logged. ```javascript import got from 'got' export default ({ log, fooApi = 'https://example.com' }) => async (id = 'foo', page = 1) => { const query = { page: parseInt(page) } log.debug({ query, id }) return got(`${fooApi}/search/${id}`, { query }) } ``` -------------------------------- ### Node.js Version Management with nvm Source: https://github.com/meltwater/aws-configuration-fetcher/blob/master/README.md Instructions for managing Node.js versions using nvm, including installing a specific version and setting it as the active version for shell sessions. ```bash $ nvm install $ nvm use ``` -------------------------------- ### Install aws-configuration-fetcher using npm or Yarn Source: https://github.com/meltwater/aws-configuration-fetcher/blob/master/README.md Instructions for adding the aws-configuration-fetcher package as a dependency to your project using either npm or Yarn package managers. ```bash $ npm install @meltwater/aws-configuration-fetcher ``` ```bash $ yarn add @meltwater/aws-configuration-fetcher ``` -------------------------------- ### Debug Example Code with Breakpoints Source: https://github.com/meltwater/aws-configuration-fetcher/blob/master/examples/README.md Demonstrates how to insert a debugger statement into an exported example function. This allows developers to pause execution and inspect the state when running in debug mode. ```javascript export default ({ log }) => async () => { debugger // ... } ``` -------------------------------- ### Adapt Fetched Configuration Values Source: https://github.com/meltwater/aws-configuration-fetcher/blob/master/README.md Illustrates how to use the 'adapter' function within ConfigurationRequest to transform or validate fetched configuration values. Examples include validating for empty strings and parsing values to integers. ```javascript import { createConfigurationRepository, ConfigurationRequest, ConfigurationRequestTypes } from '@meltwater/aws-configuration-fetcher' const configurationRepository = createConfigurationRepository() const configuration = configurationRepository.getConfiguration([ new ConfigurationRequest({ adapter: (value) => { if(value.trim() === '') { throw new Error('The magic has faded, because the parameter value was empty.') } return value }, key: '/some/magical/parameter/path', propertyName: 'someMagicalParameter', type: ConfigurationRequestTypes.ssm }), new ConfigurationRequest({ adapter: (value) => parseInt(value) key: 'something-super-secret', propertyName: 'somethingSuperSecret', type: ConfigurationRequestTypes.secret }) ]) ``` -------------------------------- ### Utilize ConfigurationRequestTypes Enum in JavaScript Source: https://context7.com/meltwater/aws-configuration-fetcher/llms.txt Shows how to use the ConfigurationRequestTypes enumeration to identify and validate different configuration source types. Includes examples of logging available types and checking type validity. ```javascript import { ConfigurationRequestTypes } from '@meltwater/aws-configuration-fetcher' // Available types console.log(ConfigurationRequestTypes.ssm) // 'ssm' - AWS SSM Parameter Store console.log(ConfigurationRequestTypes.secret) // 'secret' - AWS Secrets Manager console.log(ConfigurationRequestTypes.local) // 'local' - Local pass-through value // Validate a type const isValidType = ConfigurationRequestTypes.isValid('ssm') console.log(isValidType) // true const isInvalidType = ConfigurationRequestTypes.isValid('redis') console.log(isInvalidType) // false // Example: Dynamic type selection function createDynamicRequest(source, key, propertyName) { if (!ConfigurationRequestTypes.isValid(source)) { throw new Error(`Unsupported configuration source: ${source}`) } return new ConfigurationRequest({ key, propertyName, type: source }) } ``` -------------------------------- ### Initialize Configuration Repository with createConfigurationRepository Source: https://context7.com/meltwater/aws-configuration-fetcher/llms.txt Demonstrates how to initialize the configuration repository using the factory function. It covers both default settings and advanced configurations including custom cache managers and specific AWS SDK clients. ```javascript import { createConfigurationRepository, ConfigurationRequest, ConfigurationRequestTypes } from '@meltwater/aws-configuration-fetcher'; import cacheManager from 'cache-manager'; import AWS from 'aws-sdk'; const configRepo = createConfigurationRepository({}); const customCache = cacheManager.caching({ store: 'memory', max: 100, ttl: 300 }); const customConfigRepo = createConfigurationRepository({ cache: customCache, cacheKey: 'my-app-config', log: console, smClient: new AWS.SecretsManager({ region: 'us-east-1' }), ssmClient: new AWS.SSM({ region: 'us-east-1' }) }); const config = await customConfigRepo.getConfiguration([ new ConfigurationRequest({ key: '/myapp/database/host', propertyName: 'dbHost', type: ConfigurationRequestTypes.ssm }) ]); console.log(config.dbHost); ``` -------------------------------- ### Retrieve Configuration Values with getConfiguration Source: https://context7.com/meltwater/aws-configuration-fetcher/llms.txt Shows how to fetch multiple configuration values in parallel from different sources including SSM, Secrets Manager, and local values using the getConfiguration method. ```javascript import { createConfigurationRepository, ConfigurationRequest, ConfigurationRequestTypes } from '@meltwater/aws-configuration-fetcher'; const configRepo = createConfigurationRepository({}); const configuration = await configRepo.getConfiguration([ new ConfigurationRequest({ key: '/production/api/endpoint', propertyName: 'apiEndpoint', type: ConfigurationRequestTypes.ssm }), new ConfigurationRequest({ key: 'prod/database/credentials', propertyName: 'dbCredentials', type: ConfigurationRequestTypes.secret }), new ConfigurationRequest({ key: 'https://api.example.com', propertyName: 'fallbackUrl', type: ConfigurationRequestTypes.local }) ]); console.log(configuration.apiEndpoint); console.log(configuration.dbCredentials); console.log(configuration.fallbackUrl); ``` -------------------------------- ### Define ConfigurationRequest in JavaScript Source: https://context7.com/meltwater/aws-configuration-fetcher/llms.txt Demonstrates how to create ConfigurationRequest objects for various sources like SSM parameters, secrets, and local values. It shows basic usage and how to apply custom adapters for value transformation and validation. ```javascript import { ConfigurationRequest, ConfigurationRequestTypes } from '@meltwater/aws-configuration-fetcher' // Basic SSM parameter request const ssmRequest = new ConfigurationRequest({ key: '/app/config/timeout', propertyName: 'timeout', type: ConfigurationRequestTypes.ssm }) // Secret with JSON parsing adapter const secretRequest = new ConfigurationRequest({ key: 'app/database/credentials', propertyName: 'dbConfig', type: ConfigurationRequestTypes.secret, adapter: (value) => JSON.parse(value) }) // SSM parameter with integer conversion and validation const portRequest = new ConfigurationRequest({ key: '/app/config/port', propertyName: 'port', type: ConfigurationRequestTypes.ssm, adapter: (value) => { const port = parseInt(value, 10) if (isNaN(port) || port < 1 || port > 65535) { throw new Error(`Invalid port number: ${value}`) } return port } }) // Local value with validation const localRequest = new ConfigurationRequest({ key: 'default-region', propertyName: 'region', type: ConfigurationRequestTypes.local, adapter: (value) => { if (!value || value.trim() === '') { throw new Error('Region cannot be empty') } return value.trim() } }) ``` -------------------------------- ### Create Configuration Request Factories Source: https://github.com/meltwater/aws-configuration-fetcher/blob/master/snapshots/lib/configuration-request-factories.spec.js.md Demonstrates the expected structure of ConfigurationRequest objects generated by the factory methods. These snapshots verify that the adapter, key, propertyName, and type fields are correctly populated for SSM, local, and secret configurations. ```javascript const ssmReq = createSsmStringConfigurationRequest('the/path', 'theName'); const localReq = createLocalStringConfigurationRequest('the/path', 'theName'); const secretReq = createSecretStringConfigurationRequest('the/path', 'theName'); ``` -------------------------------- ### Fetch Configuration from AWS SSM and Secrets Manager Source: https://github.com/meltwater/aws-configuration-fetcher/blob/master/README.md Demonstrates how to use the createConfigurationRepository and ConfigurationRequest classes to fetch parameters from AWS SSM and Secrets Manager. It shows how to define requests for specific keys and property names, and how to access the retrieved configuration. ```javascript import { createConfigurationRepository, ConfigurationRequest, ConfigurationRequestTypes } from '@meltwater/aws-configuration-fetcher' const configurationRepository = createConfigurationRepository() const configuration = configurationRepository.getConfiguration([ new ConfigurationRequest({ key: '/some/magical/parameter/path', propertyName: 'someMagicalParameter', type: ConfigurationRequestTypes.ssm }), new ConfigurationRequest({ key: 'something-super-secret', propertyName: 'somethingSuperSecret', type: ConfigurationRequestTypes.secret }) ]) console.log(configuration.someMagicalParameter) console.log(configuration.somethingSuperSecret, 'Maybe I should not log this...') ``` -------------------------------- ### createConfigurationRepository Source: https://context7.com/meltwater/aws-configuration-fetcher/llms.txt Factory function to initialize the configuration repository with custom AWS clients and caching strategies. ```APIDOC ## Factory: createConfigurationRepository ### Description Initializes a new ConfigurationRepository instance. This is the entry point for the library, allowing configuration of AWS SDK clients, cache managers, and logging. ### Parameters #### Request Body - **cache** (Object) - Optional - Cache manager instance (e.g., cache-manager). - **cacheKey** (String) - Optional - Unique key for caching the configuration results. - **log** (Object) - Optional - Logger instance (e.g., pino, console). - **smClient** (Object) - Optional - AWS Secrets Manager client instance. - **ssmClient** (Object) - Optional - AWS SSM client instance. ### Request Example { "cacheKey": "my-app-config", "log": "console" } ``` -------------------------------- ### Clone the aws-configuration-fetcher source code Source: https://github.com/meltwater/aws-configuration-fetcher/blob/master/README.md Command to clone the source code repository for the aws-configuration-fetcher project from GitHub. ```bash $ git clone git@github.com:meltwater/aws-configuration-fetcher.git ``` -------------------------------- ### Configure Local Environment Settings Source: https://github.com/meltwater/aws-configuration-fetcher/blob/master/examples/README.md Defines the structure for local configuration files used by the project. This JSON file allows setting log levels and output modes to control runtime behavior. ```json { "logLevel": "info", "logFilter": null, "logOutputMode": "short" } ``` -------------------------------- ### Consistent Response Format Source: https://github.com/meltwater/aws-configuration-fetcher/blob/master/snapshots/lib/configuration-repository.spec.js.md This snippet illustrates the expected consistent format for responses from the configuration fetcher. It ensures that regardless of the specific configuration fetched, the data is returned in a predictable structure, aiding in easier parsing and integration. ```json { "somOtherProperty": "someOtherPropertyValue", "someProperty": "somePropertyValue" } ``` -------------------------------- ### ConfigurationRepository.getConfiguration Source: https://context7.com/meltwater/aws-configuration-fetcher/llms.txt Retrieves configuration values from defined sources (SSM, Secrets Manager, or Local) asynchronously. ```APIDOC ## Method: getConfiguration ### Description Asynchronously fetches configuration values based on an array of ConfigurationRequest objects. Executes requests in parallel and returns a mapped object. ### Parameters #### Request Body - **requests** (Array) - Required - An array of request objects defining the key, propertyName, and source type (ssm, secret, or local). ### Request Example [ { "key": "/production/api/endpoint", "propertyName": "apiEndpoint", "type": "ssm" } ] ### Response #### Success Response (200) - **Object** - Returns an object where keys are the 'propertyName' values provided in the request. ``` -------------------------------- ### Create Validated SSM String Requests with JavaScript Source: https://context7.com/meltwater/aws-configuration-fetcher/llms.txt Provides a factory function, `createSsmStringConfigurationRequest`, to simplify the creation of ConfigurationRequests for SSM string parameters. It includes built-in validation to ensure the retrieved string is not empty or whitespace. ```javascript import { createConfigurationRepository, createSsmStringConfigurationRequest } from '@meltwater/aws-configuration-fetcher' const configRepo = createConfigurationRepository({}) // Create validated SSM string requests const configuration = await configRepo.getConfiguration([ createSsmStringConfigurationRequest('apiKey', '/myapp/api-key'), createSsmStringConfigurationRequest('dbHost', '/myapp/database/host'), createSsmStringConfigurationRequest('environment', '/myapp/env') ]) // All values are guaranteed to be non-empty strings console.log(configuration.apiKey) // Throws if empty console.log(configuration.dbHost) // Throws if whitespace-only console.log(configuration.environment) // Validated string value ``` -------------------------------- ### Create Local String Configuration Request (JavaScript) Source: https://context7.com/meltwater/aws-configuration-fetcher/llms.txt Factory function to create a ConfigurationRequest for local string values with built-in non-empty validation. This is useful for environment-specific defaults or fallback values. ```javascript import { createConfigurationRepository, createLocalStringConfigurationRequest } from '@meltwater/aws-configuration-fetcher' const configRepo = createConfigurationRepository({}) // Create validated local value requests const configuration = await configRepo.getConfiguration([ createLocalStringConfigurationRequest('defaultRegion', 'us-east-1'), createLocalStringConfigurationRequest('appName', 'my-application'), createLocalStringConfigurationRequest('logLevel', process.env.LOG_LEVEL || 'info') ]) // All values are passed through with validation console.log(configuration.defaultRegion) // 'us-east-1' console.log(configuration.appName) // 'my-application' console.log(configuration.logLevel) // From environment or 'info' ``` -------------------------------- ### ConfigurationRequest Class Source: https://context7.com/meltwater/aws-configuration-fetcher/llms.txt Defines a request for a single configuration value, specifying the source, key, property name, and optional transformation/validation logic. ```APIDOC ## ConfigurationRequest Class representing a request for a single configuration value. It encapsulates the source type, key path, output property name, and optional adapter function for value transformation or validation. ### Example Usage ```javascript import { ConfigurationRequest, ConfigurationRequestTypes } from '@meltwater/aws-configuration-fetcher' // Basic SSM parameter request const ssmRequest = new ConfigurationRequest({ key: '/app/config/timeout', propertyName: 'timeout', type: ConfigurationRequestTypes.ssm }) // Secret with JSON parsing adapter const secretRequest = new ConfigurationRequest({ key: 'app/database/credentials', propertyName: 'dbConfig', type: ConfigurationRequestTypes.secret, adapter: (value) => JSON.parse(value) }) // SSM parameter with integer conversion and validation const portRequest = new ConfigurationRequest({ key: '/app/config/port', propertyName: 'port', type: ConfigurationRequestTypes.ssm, adapter: (value) => { const port = parseInt(value, 10) if (isNaN(port) || port < 1 || port > 65535) { throw new Error(`Invalid port number: ${value}`) } return port } }) // Local value with validation const localRequest = new ConfigurationRequest({ key: 'default-region', propertyName: 'region', type: ConfigurationRequestTypes.local, adapter: (value) => { if (!value || value.trim() === '') { throw new Error('Region cannot be empty') } return value.trim() } }) ``` ``` -------------------------------- ### createSsmStringConfigurationRequest Factory Source: https://context7.com/meltwater/aws-configuration-fetcher/llms.txt A factory function that simplifies creating a `ConfigurationRequest` for SSM parameters. It includes built-in validation to ensure the retrieved string value is not empty or whitespace-only. ```APIDOC ## createSsmStringConfigurationRequest Factory function that creates a ConfigurationRequest for SSM parameters with built-in non-empty string validation. Throws an error if the retrieved value is empty or whitespace-only. ### Example Usage ```javascript import { createConfigurationRepository, createSsmStringConfigurationRequest } from '@meltwater/aws-configuration-fetcher' const configRepo = createConfigurationRepository({}) // Create validated SSM string requests const configuration = await configRepo.getConfiguration([ createSsmStringConfigurationRequest('apiKey', '/myapp/api-key'), createSsmStringConfigurationRequest('dbHost', '/myapp/database/host'), createSsmStringConfigurationRequest('environment', '/myapp/env') ]) // All values are guaranteed to be non-empty strings console.log(configuration.apiKey) // Throws if empty console.log(configuration.dbHost) // Throws if whitespace-only console.log(configuration.environment) // Validated string value ``` ``` -------------------------------- ### Define Custom Log Filters Source: https://github.com/meltwater/aws-configuration-fetcher/blob/master/examples/README.md Provides a template for creating log filters that can be used to restrict output. Filters are exported as an object and applied via environment variables. ```javascript const onlyFooBar = (log) => log.foo === 'bar' export default { onlyFooBar } ``` -------------------------------- ### ConfigurationRequestTypes Enum Source: https://context7.com/meltwater/aws-configuration-fetcher/llms.txt An enumeration object defining the available configuration source types (SSM, Secrets Manager, Local) and includes a method to validate if a given string is a recognized type. ```APIDOC ## ConfigurationRequestTypes Enumeration object defining the available configuration source types. It includes a validation method to check if a given string is a valid type. ### Available Types - `ssm`: AWS SSM Parameter Store - `secret`: AWS Secrets Manager - `local`: Local pass-through value ### Example Usage ```javascript import { ConfigurationRequestTypes } from '@meltwater/aws-configuration-fetcher' // Available types console.log(ConfigurationRequestTypes.ssm) // 'ssm' console.log(ConfigurationRequestTypes.secret) // 'secret' console.log(ConfigurationRequestTypes.local) // 'local' // Validate a type const isValidType = ConfigurationRequestTypes.isValid('ssm') console.log(isValidType) // true const isInvalidType = ConfigurationRequestTypes.isValid('redis') console.log(isInvalidType) // false // Example: Dynamic type selection function createDynamicRequest(source, key, propertyName) { if (!ConfigurationRequestTypes.isValid(source)) { throw new Error(`Unsupported configuration source: ${source}`) } return new ConfigurationRequest({ key, propertyName, type: source }) } ``` ``` -------------------------------- ### Create Validated Secret String Requests with JavaScript Source: https://context7.com/meltwater/aws-configuration-fetcher/llms.txt Offers a factory function, `createSecretStringConfigurationRequest`, for generating ConfigurationRequests for AWS Secrets Manager string secrets. This function enforces that the secret value is non-empty. ```javascript import { createConfigurationRepository, createSecretStringConfigurationRequest } from '@meltwater/aws-configuration-fetcher' const configRepo = createConfigurationRepository({}) // Create validated secret requests const configuration = await configRepo.getConfiguration([ createSecretStringConfigurationRequest('dbPassword', 'prod/db/password'), createSecretStringConfigurationRequest('apiSecret', 'prod/api/secret'), createSecretStringConfigurationRequest('jwtSigningKey', 'prod/jwt/key') ]) // All secrets are guaranteed to be non-empty strings console.log(configuration.dbPassword) // Database password from Secrets Manager console.log(configuration.apiSecret) // API secret value console.log(configuration.jwtSigningKey) // JWT signing key ``` -------------------------------- ### createSecretStringConfigurationRequest Factory Source: https://context7.com/meltwater/aws-configuration-fetcher/llms.txt A factory function for creating `ConfigurationRequest` objects specifically for AWS Secrets Manager. It enforces that the retrieved secret value is a non-empty string. ```APIDOC ## createSecretStringConfigurationRequest Factory function that creates a ConfigurationRequest for AWS Secrets Manager with built-in non-empty string validation. Ensures the secret value exists and is not empty. ### Example Usage ```javascript import { createConfigurationRepository, createSecretStringConfigurationRequest } from '@meltwater/aws-configuration-fetcher' const configRepo = createConfigurationRepository({}) // Create validated secret requests const configuration = await configRepo.getConfiguration([ createSecretStringConfigurationRequest('dbPassword', 'prod/db/password'), createSecretStringConfigurationRequest('apiSecret', 'prod/api/secret'), createSecretStringConfigurationRequest('jwtSigningKey', 'prod/jwt/key') ]) // All secrets are guaranteed to be non-empty strings console.log(configuration.dbPassword) // Database password from Secrets Manager console.log(configuration.apiSecret) // API secret value console.log(configuration.jwtSigningKey) // JWT signing key ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.