Trick: Share config values for Front and Back

This is TypeScript, easily convertible to JS.

/** I store config values which are needed on front and back in the CSS, because
 * the CSS is accessible from front and back.
 *
 * Example:
   CSS:
   :root {
     --skipUndueCards: false;
   }
   TS: CssVars.asBoolean("--skipUndueCards") !== true
 */
namespace CssVars {
  import toBoolean = HelgeUtils.Types.SafeConversions.toBoolean;
  import TypeException = HelgeUtils.Types.TypeException;

  export const asString = (varName: string):string => {
    const propertyValue: string =
        getComputedStyle(document.documentElement).getPropertyValue(varName)
    ;
    return propertyValue
  }

  export const asBoolean = (varName: string): boolean => {
    const resultAsString = asString(varName)
    try {
      return toBoolean(resultAsString)
    } catch (e) {
      throw new TypeException(`CSS var ${varName
        } does not contain a boolean: "${resultAsString
        }"`)
    }
  }

  export const asNumber = (varName: string): number => {
    const resultAsString = asString(varName)
    const result = parseFloat(resultAsString)
    if (isNaN(result)) {
      throw new Error(`CSS var ${varName
      } does not contain a number: "${resultAsString
      }"`)
    }
    return result
  }
}

export namespace HelgeUtils {
  export namespace Types {
    export class TypeException extends Error {
      constructor(message: string) {
        super(message)
        this.name = "MyCustomException"
      }
    }

    export namespace SafeConversions {
      export const toNumber = (input: string): number => {
        const result = parseFloat(input)
        if (isNaN(result)) {
          throw new Error(`Not a number: "${input}"`)
        }
        return result
      }

      export const toBoolean = (resultAsString: string) => {
        switch (resultAsString.trim()) {
          case "t":
          case "true":
            return true
          case "f":
          case "false":
            return false
          default:
            throw new TypeException(`Not a boolean: "${resultAsString}"`)
        }
      }
    }
  }
}

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.