or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

appconfig.mdbase.mddynamodb.mdindex.mdsecrets.mdssm.md
tile.json

base.mddocs/

Base Provider and Utilities

Abstract base class for implementing custom parameter providers, along with utilities for managing caching behavior.

← Back to Overview

API Reference

abstract class BaseProvider {
  protected client: unknown;
  protected store: Map<string, ExpirableValue>;

  constructor(config: BaseProviderConstructorOptions);
  get(name: string, options?: GetOptionsInterface): Promise<unknown>;
  getMultiple(path: string, options?: GetMultipleOptionsInterface): Promise<unknown>;
  addToCache(key: string, value: unknown, maxAge: number): void;
  clearCache(): void;
  hasKeyExpiredInCache(key: string): boolean;
  protected abstract _get(name: string, options?: unknown): Promise<unknown>;
  protected abstract _getMultiple(path: string, options?: unknown): Promise<Record<string, unknown> | undefined>;
}

interface BaseProviderConstructorOptions {
  awsSdkV3Client?: unknown;
  clientConfig?: unknown;
  awsSdkV3ClientPrototype?: new (config?: unknown) => unknown;
}

function clearCaches(): void;  // Clears all default provider caches
const DEFAULT_PROVIDERS: Record<string, BaseProviderInterface>;

class GetOptions {
  forceFetch: boolean;
  maxAge: number;
  sdkOptions: unknown;
  transform: TransformOptions;
  constructor(options?: GetOptionsInterface);
}

class GetMultipleOptions extends GetOptions {
  throwOnTransformError: boolean;
  constructor(options?: GetMultipleOptionsInterface);
}

Creating Custom Providers

Extend BaseProvider to create custom parameter providers. Base class handles caching, transformation, and expiration automatically.

Steps:

  1. Extend BaseProvider
  2. Implement _get(name, options) for single value retrieval
  3. Implement _getMultiple(path, options) for batch retrieval
  4. Call super(config) with client configuration

Example: HTTP API Provider

import { BaseProvider } from '@aws-lambda-powertools/parameters/base';
import type { GetOptionsInterface, GetMultipleOptionsInterface } from '@aws-lambda-powertools/parameters/base/types';

class HttpParameterProvider extends BaseProvider {
  private apiUrl: string;

  constructor(apiUrl: string) {
    super({});
    this.apiUrl = apiUrl;
  }

  protected async _get(name: string, options?: GetOptionsInterface): Promise<unknown> {
    const response = await fetch(`${this.apiUrl}/parameters/${name}`);
    if (!response.ok) throw new Error(`Failed to fetch parameter: ${name}`);
    return response.text();
  }

  protected async _getMultiple(
    path: string,
    options?: GetMultipleOptionsInterface
  ): Promise<Record<string, unknown> | undefined> {
    const response = await fetch(`${this.apiUrl}/parameters?path=${path}`);
    if (!response.ok) throw new Error(`Failed to fetch parameters: ${path}`);
    return response.json();
  }
}

// Usage - caching handled by base class
const provider = new HttpParameterProvider('https://api.example.com');
const param = await provider.get('my-param', { maxAge: 300 });
const params = await provider.getMultiple('/my/path', { transform: 'json' });

Example: Redis Provider

import { BaseProvider } from '@aws-lambda-powertools/parameters/base';
import type { GetOptionsInterface, GetMultipleOptionsInterface } from '@aws-lambda-powertools/parameters/base/types';
import { createClient, RedisClientType } from 'redis';

class RedisProvider extends BaseProvider {
  protected client: RedisClientType;

  constructor(redisUrl: string) {
    const redisClient = createClient({ url: redisUrl });
    super({ awsSdkV3Client: redisClient });
    this.client = redisClient;
  }

  async connect(): Promise<void> {
    await this.client.connect();
  }

  protected async _get(name: string, options?: GetOptionsInterface): Promise<unknown> {
    const value = await this.client.get(name);
    return value === null ? undefined : value;
  }

  protected async _getMultiple(
    path: string,
    options?: GetMultipleOptionsInterface
  ): Promise<Record<string, unknown> | undefined> {
    const keys = await this.scanKeys(`${path}*`);
    if (keys.length === 0) return undefined;

    const values = await this.client.mGet(keys);
    const result: Record<string, unknown> = {};
    keys.forEach((key, index) => {
      if (values[index] !== null) result[key] = values[index];
    });
    return result;
  }

  private async scanKeys(pattern: string): Promise<string[]> {
    const keys: string[] = [];
    let cursor = 0;
    do {
      const result = await this.client.scan(cursor, { MATCH: pattern, COUNT: 100 });
      cursor = result.cursor;
      keys.push(...result.keys);
    } while (cursor !== 0);
    return keys;
  }
}

// Usage
const provider = new RedisProvider('redis://localhost:6379');
await provider.connect();
const value = await provider.get('config:api-url', { maxAge: 300 });
const configs = await provider.getMultiple('config:', { transform: 'auto' });

Clear Caches Utility

Clears all caches of default provider instances used by high-level functions.

import { clearCaches } from '@aws-lambda-powertools/parameters';
import { getParameter } from '@aws-lambda-powertools/parameters/ssm';
import { getSecret } from '@aws-lambda-powertools/parameters/secrets';

// Fetch parameters (cached)
const param1 = await getParameter('/my/param');
const secret1 = await getSecret('my-secret');

// Clear all default provider caches
clearCaches();

// Next fetch retrieves fresh values
const param2 = await getParameter('/my/param');
const secret2 = await getSecret('my-secret');

Testing pattern:

import { clearCaches } from '@aws-lambda-powertools/parameters';

describe('Parameter tests', () => {
  afterEach(() => {
    clearCaches(); // Ensure isolation between tests
  });

  it('should retrieve parameter', async () => {
    // Test code
  });
});

Cache Implementation

Cache structure:

  • Uses Map<string, ExpirableValue> for storage
  • Each entry contains value and TTL
  • Cache keys include parameter name and retrieval options

Cache methods:

provider.addToCache(key: string, value: unknown, maxAge: number): void
provider.hasKeyExpiredInCache(key: string): boolean
provider.clearCache(): void

Expirable value:

class ExpirableValue {
  value: unknown;
  ttl: number; // Expiration timestamp in milliseconds
  constructor(value: unknown, maxAge: number);
  isExpired(): boolean;
}

Environment Variables

POWERTOOLS_PARAMETERS_MAX_AGE: Default cache TTL (seconds) when maxAge not provided

export POWERTOOLS_PARAMETERS_MAX_AGE=60
const param = await getParameter('/my/param'); // Uses env var TTL

Type Definitions

type TransformOptions = 'json' | 'binary' | 'auto';

interface ExpirableValueInterface {
  value: unknown;
  ttl: number;
}

interface BaseProviderInterface {
  get(name: string, options?: GetOptionsInterface): Promise<unknown>;
  getMultiple(path: string, options?: GetMultipleOptionsInterface): Promise<unknown>;
  clearCache?(): void;
}