All files / src/utils/hooks useConfig.ts

93.33% Statements 14/15
100% Branches 4/4
100% Functions 5/5
93.33% Lines 14/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65                              66x                                       108x 108x       66x         189x 189x 189x   189x 39x   17x       23x 23x 23x       189x    
import { SERVER_URL } from '@config/base';
import { requestUrlAndGetPromise } from '@utils/FetchUtils';
import { useEffect, useState } from 'react';
 
type ConfigValueTypes = string | number | boolean;
 
export interface ConfigResponseProps {
  key: string;
  value: ConfigValueTypes;
  type: string;
}
 
export type ConfigKey = keyof typeof configKeyToTypeMap;
export type ConfigType = typeof configKeyToTypeMap[ConfigKey];
 
const configKeyToTypeMap = {
  'register.self_register': 'boolean',
  'register.reset_password': 'boolean',
  'feedback.enable_types': 'string',
  "feedback.user_manual_link": 'string',
  "feedback.developer_manual_link": 'string',
  "ai.assistant.enable": 'boolean',
  "websocket.heartbeatInterval": 'int',
  "attachment.align_download_permission_with_update": 'boolean',
  "debugDynamicLogic.enableNewDomainChangePushService": 'string',
};
 
/**
 * Fetches the config from the server
 * @param configKey config key
 * @param configType data type of the config, like boolean, integer, string etc
 */
export async function fetchConfig(configKey: ConfigKey, configType?: ConfigType): Promise<ConfigResponseProps> {
  // q:how to get the name of a type in typescript?
  // a: https://stackoverflow.com/questions/39645871/how-to-get-the-name-of-a-type-in-typescript
  const url = `${SERVER_URL}/config/${configKey}/${configType ?? 'string'}`;
  return requestUrlAndGetPromise(url, {});
}
 
// Define useConfig hook
export const useConfig = (configKey: ConfigKey, configType?: ConfigType): {
  value: ConfigValueTypes | null;
  error: Error | null;
  loading: boolean;
} => {
  const [value, setValue] = useState<ConfigValueTypes | null>(null);
  const [error, setError] = useState<Error | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
 
  useEffect(() => {
    fetchConfig(configKey, configType ?? configKeyToTypeMap[configKey])
      .then((config) => {
        setValue(config.value);
        setLoading(false);
      })
      .catch((error) => {
        console.error(`Failed to fetch config for ${configKey}: ${error}`);
        setError(error);
        setLoading(false);
      });
  }, [configKey, configType]);
 
  return { value, error, loading };
};