config-manager.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /**
  2. * Available configuration sources
  3. */
  4. export const ConfigSource = {
  5. env: 'env',
  6. db: 'db',
  7. } as const;
  8. export type ConfigSource = (typeof ConfigSource)[keyof typeof ConfigSource];
  9. /**
  10. * Metadata for a configuration value
  11. */
  12. export interface ConfigDefinition<T> {
  13. defaultValue: T;
  14. envVarName?: string;
  15. isSecret?: boolean;
  16. }
  17. /**
  18. * Helper function for defining configurations with type safety
  19. */
  20. export const defineConfig = <T>(
  21. config: ConfigDefinition<T>,
  22. ): ConfigDefinition<T> => config;
  23. /**
  24. * Interface for loading configuration values
  25. */
  26. // biome-ignore lint/suspicious/noExplicitAny: ignore
  27. export interface IConfigLoader<K extends string, V extends Record<K, any>> {
  28. /**
  29. * Load configurations from environment variables
  30. */
  31. loadFromEnv(): Promise<RawConfigData<K, V>>;
  32. /**
  33. * Load configurations from database
  34. */
  35. loadFromDB(): Promise<RawConfigData<K, V>>;
  36. }
  37. // biome-ignore lint/suspicious/noExplicitAny: ignore
  38. export type RawConfigData<K extends string, V extends Record<K, any>> = Record<
  39. K,
  40. {
  41. value: V[K];
  42. definition?: ConfigDefinition<V[K]>;
  43. }
  44. >;
  45. export type UpdateConfigOptions = {
  46. skipPubsub?: boolean;
  47. removeIfUndefined?: boolean;
  48. };
  49. /**
  50. * Interface for managing configuration values
  51. */
  52. // biome-ignore lint/suspicious/noExplicitAny: ignore
  53. export interface IConfigManager<K extends string, V extends Record<K, any>> {
  54. /**
  55. * Load configurations
  56. * @param options.source - Specify which source to load from
  57. */
  58. loadConfigs(options?: { source?: ConfigSource }): Promise<void>;
  59. /**
  60. * Get a configuration value
  61. */
  62. getConfig<T extends K>(key: T, source?: ConfigSource): V[T];
  63. /**
  64. * Update a configuration value
  65. */
  66. updateConfig<T extends K>(
  67. key: T,
  68. value: V[T],
  69. options?: UpdateConfigOptions,
  70. ): Promise<void>;
  71. /**
  72. * Update multiple configuration values
  73. */
  74. updateConfigs(
  75. updates: Partial<{ [T in K]: V[T] }>,
  76. options?: UpdateConfigOptions,
  77. ): Promise<void>;
  78. /**
  79. * Remove multiple configuration values
  80. */
  81. removeConfigs(keys: K[], options?: UpdateConfigOptions): Promise<void>;
  82. /**
  83. * Get environment variables managed with ConfigDefinitions
  84. */
  85. getManagedEnvVars(showSecretValues: boolean): Record<string, string>;
  86. }