Options
All
  • Public
  • Public/Protected
  • All
Menu

Module @sap/cloud-sdk-util

cloud-sdk-utils

Package that contains general utility functions that we reuse multiple times in the SDK. While primarily designed for internal usage, they might also be benefical for consumers of the SDK.

Helpful Links

Index

Type aliases

LogLevel

LogLevel: "error" | "warn" | "info" | "verbose" | "debug" | "silly"

Npm log levels used for the SAP Cloud SDK logger.

Variables

Const VALUE_IS_UNDEFINED

VALUE_IS_UNDEFINED: "VALUE_IS_UNDEFINED" = "VALUE_IS_UNDEFINED"

Const cloudSdkExceptionLogger

cloudSdkExceptionLogger: Logger = container.get(exceptionLoggerId, {defaultMeta: { logger: loggerReference, test: 'exception' },format,exceptionHandlers: [exceptionTransport]})

Default logger for the SAP Cloud SDK for unhandled exceptions.

Const kibana

kibana: Format = combine(timestamp(),format(info => ({...info,msg: info.message,written_ts: new Date(info.timestamp).getTime(),written_at: info.timestamp}))(),json())

Format for logging in Kibana.

Const local

local: Format = combine(timestamp(),format(info => ({...info,level: info.level.toUpperCase()}))(),cli(),printf(info => {const messageContext = info.custom_fields && info.custom_fields.messageContext ? `${chalk.blue(`(${info.custom_fields.messageContext})`)}: ` : '';const trimmedMessage = info.message.replace(/^\s*/, '');const paddingLength = info.message.length - trimmedMessage.length + messageContext.length;if (info.error) {info.level = chalk.inverse(info.level);}return `${chalk.gray(`[${info.timestamp}]`)} ${info.level} ${messageContext.padStart(paddingLength, ' ')}${trimmedMessage}`;}))

Format for local logging.

Functions

Const assocSome

  • assocSome<T>(key: string, value?: any): (Anonymous function)
  • Calls rambda's assoc function if the provided value is neither null nor undefined. Note that this is different to JS idiomatic checks for truthy/falsy values, i.e. an empty string will result in assoc being called.

    Type parameters

    • T

    Parameters

    • key: string

      The key to associate with the given value.

    • Optional value: any

      The value to associate with the given key.

    Returns (Anonymous function)

    A copy of the input object with the new key-value pair if the value is neither null nor undefined.

Const asyncPipe

  • asyncPipe(...fns: any[]): (Anonymous function)
  • Works similar to Ramdas pipe function, but works on promises, which allows using async functions.

    Parameters

    • Rest ...fns: any[]

      The functions to be chained.

    Returns (Anonymous function)

createLogger

  • Create a logger for the given message context, if available.

    Usage: To create a logger in your module, it is recommended to pass a module identifier that will be logged as messageContext for all messages from this logger: const logger = createLogger('my-module');. Not setting any module identifier will retrieve the default logger. Use this logger throughout your module. If the module is spread over multiple files, you can retrieve the logger instance by calling the createLogger function with the respective module identifier. There will always be only one instance of a logger per module identifier. You can pass any custom data that you want to be logged in addition by passing an object instead. You can change the default logging level (INFO) using the level key in the object. In those cases, provide the messageContext as a key in the object:

    const logger = createLogger({
      messageContext: 'my-module',
      myCustomKey: 'my-custom-data',
      level: 'debug'
    });

    You will find these information under the custom_fields key in your Cloud Foundry logs.

    To retrieve a logger after its creation use getLogger. If you want to change the log level of a logger use setLogLevel.

    Parameters

    • Optional messageContext: string | MessageContextObj & LoggerOptions

      Either a key for the message context of all messages produced by the logger or an object with additional keys to set in the message.

    Returns Logger

    A newly created or an already existing logger for the given context.

disableExceptionLogger

  • disableExceptionLogger(): void
  • Disable logging of exceptions. Enabled by default.

    Returns void

enableExceptionLogger

  • enableExceptionLogger(): void
  • Enable logging of exceptions. Enabled by default.

    Returns void

encodeBase64

  • encodeBase64(str: string): string
  • Encodes the given string in base64.

    Parameters

    • str: string

      Input string.

    Returns string

    Base64 string.

errorWithCause

  • errorWithCause(message: string, cause: Error): Error
  • Creates a new error using the provided message and appends the causes stacktrace to the new error's stacktrace.

    Parameters

    • message: string

      The message of the new error.

    • cause: Error

      The original error.

    Returns Error

    A new error instance.

findProjectRoot

  • findProjectRoot(path: string, lastPath?: string): string
  • Parameters

    • path: string
    • Default value lastPath: string = path

    Returns string

flat

  • flat<T>(arr: T[][]): T[]
  • Flatten a multidimensional array

    Type parameters

    • T

    Parameters

    • arr: T[][]

      Multidimensional array to be flattened

    Returns T[]

    Flattened array

getLogger

  • getLogger(messageContext?: string): Logger | undefined
  • Get logger for a given message context, if avilable.

    Parameters

    • Default value messageContext: string = DEFAULT_LOGGER__MESSAGE_CONTEXT

      A key for the message context of all messages produced by the logger

    Returns Logger | undefined

    The logger for the given messageContext if it was created before

Const mergeSome

  • mergeSome(a: MapType<any>, b?: MapType<any>): MapType<any>
  • Calls rambda's merge function if second object is neither null nor undefined.

    Parameters

    • a: MapType<any>

      The object to merge into.

    • Optional b: MapType<any>

      The object which to merge into a.

    Returns MapType<any>

    A copy of the merge(a, b) or a if b is undefined or null.

propertyExists

  • propertyExists(obj: object, ...properties: string[]): boolean
  • Checks if a chain of properties exists on the given object.

    Parameters

    • obj: object

      The object to be checked.

    • Rest ...properties: string[]

      Chained properties.

    Returns boolean

    True if the property chain leads to a truthy value, false otherwise.

Const renameKeys

  • renameKeys(keyMapping: MapType<string>, obj: MapType<any>): MapType<any>
  • Takes an object and returns a new object whose keys are renamed according to the provided key mapping. Any keys in the input object not present in the key mapping will be present in the output object as-is. If a key in the key mapping is not present in the input object, the output object will contain the key with value "undefined".

    Parameters

    • keyMapping: MapType<string>

      An object mapping keys of the input object to keys of the output object.

    • obj: MapType<any>

      The input object.

    Returns MapType<any>

    An object with renamed keys.

setLogLevel

  • setLogLevel(level: LogLevel, messageContextOrLogger?: string | Logger): void
  • Change the log level of a logger based on its message context. E. g., to set the log level for the destination accessor module of the SDK to debug, simply call setLogLevel('debug', 'destination-acessor').

    Parameters

    • level: LogLevel

      level to set the logger to

    • Default value messageContextOrLogger: string | Logger = DEFAULT_LOGGER__MESSAGE_CONTEXT

      Message context of the logger to change the log level for or the logger itself

    Returns void

unique

  • unique<T>(words: T[]): T[]
  • Remove all duplicates from array

    Type parameters

    • T

    Parameters

    • words: T[]

      Array of strings that might contain duplicates

    Returns T[]

    Array of unique strings