Options
All
  • Public
  • Public/Protected
  • All
Menu

Module @sap-cloud-sdk/util

SAP Cloud SDK for JavaScript Logo

@sap-cloud-sdk/util

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

Installation

$ npm install @sap-cloud-sdk/util

Usage

The util package collects useful tools that help build your SAP Cloud Platform application. For example, the following code snippet changes the log level of the destination accessor of the SDK.

import { setLogLevel } from '@sap-cloud-sdk/util';
setLogLevel('debug', 'destination-accessor');

Documentation

Getting started guide API documentation

Helpful Links

Index

Type aliases

LogLevel

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

Npm log levels used for the SAP Cloud SDK logger.

MapType

MapType<T>: Record<string, T>
deprecated

Since v1.29.0. Use Record<string, T> instead. Convenience type for JavaScript objects.

Type parameters

  • T

ODataVersion

ODataVersion: "v2" | "v4"

Denotes the OData version.

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(errors({ stack: true }),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(errors({ stack: true }),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 assoc

  • assoc<T>(key: string, value: any, obj: T): T & { [key]: any }
  • Adds a key value pair to the given objects and returns a shallow copy. If the key is already present it will be overwritten.

    Type parameters

    • T

    Parameters

    • key: string

      key to be added

    • value: any

      value to be added

    • obj: T

      object the key value pair is added to.

    Returns T & { [key]: any }

    the object with the key value pair added

Const assocSome

  • assocSome<T>(key: string, value?: any): (Anonymous function)
  • Adds the value to the object if it 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 key/value pairs beeing added.

    deprecated

    This will be removed in version 2.0 of the SDK.

    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)
  • Same as pipe but for asynchronous functions: asynvPipe(finc1,func2,...funcN)(start) executes all functions in sequence awaiting the result and piping the response through in other words await funcN(... await func2(await func1(start))...)

    deprecated

    We will remove this in version 2.0 of the SDK.

    Parameters

    • Rest ...fns: any[]

      a list of asynchronous functions to be executed in sequence

    Returns (Anonymous function)

    the reponse of the last function in the list.

caps

  • caps(oDataVersion: any): "V2" | "V4"
  • Returns the OData version in capital letters so V2 or V4.

    Parameters

    • oDataVersion: any

      OData version in lower case: 'v2' or 'v4'

    Returns "V2" | "V4"

    'V2' or 'V4'

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

enableExceptionLogger

  • enableExceptionLogger(): void

encodeBase64

  • encodeBase64(str: string): string

equal

  • equal<T>(item1: T, item2: T): boolean

equalArrays

  • equalArrays<T>(arr1: T[], arr2: T[]): boolean

equalObjects

  • equalObjects(obj1: Record<string, any>, obj2: Record<string, any>): boolean
  • Parameters

    • obj1: Record<string, any>
    • obj2: Record<string, any>

    Returns boolean

errorWithCause

  • errorWithCause(message: string, cause: Error): Error

findProjectRoot

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

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

    Returns string

first

  • first<T>(arr: T[]): T | undefined
  • Get the first item from an array. Returns undefined if the array is empty.

    Type parameters

    • T

    Parameters

    • arr: T[]

      Array to get the first item of

    Returns T | undefined

    Fist item of the array or undefined if the array was empty

flat

  • flat<T>(arr: T[][]): T[]
  • Flatten a two dimensional array into a one dimensional array

    Type parameters

    • T

    Parameters

    • arr: T[][]

      The array to be flattened.

    Returns T[]

    A one dimensional array.

Const flatten

  • flatten(input: any[]): any[]
  • Flattens a array: [1,[2,[3,4]],5] will become [1,2,3,4,5]. Non primitive values are copied by reference.

    Parameters

    • input: any[]

      array to be flattened

    Returns any[]

    the flat array.

getGlobalLogLevel

  • getGlobalLogLevel(): string | undefined

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 identity

  • identity<T>(argument: T): T
  • Identity function

    Type parameters

    • T

    Parameters

    • argument: T

      Any object

    Returns T

    the given argument without doing something

isNullish

  • isNullish(val: any): val is null | undefined
  • Checks whether a value is either null or undefined.

    Parameters

    • val: any

      Value to check

    Returns val is null | undefined

    true for null or undefined, false otherwise.

last

  • last<T>(arr: T[]): T | undefined
  • Get the last item from an array. Returns undefined if the array is empty.

    Type parameters

    • T

    Parameters

    • arr: T[]

      Array to get the last item of

    Returns T | undefined

    Last item of the array or undefined if the array was empty

mergeIgnoreCase

  • mergeIgnoreCase<LeftT, RightT>(left?: LeftT, right?: RightT): Partial<LeftT | RightT>
  • Create an object by merging the right object into a shallow copy of the left object ignoring casing, but keeping the right casing. Keys present both objects will be present in the merged object.

    Type parameters

    • LeftT: Record<string, any>

    • RightT: Record<string, any>

    Parameters

    • Default value left: LeftT = {} as LeftT

      Object to merge.

    • Default value right: RightT = {} as RightT

      Object to merge. The casing of the keys of this object takes precedence.

    Returns Partial<LeftT | RightT>

    • An object containing all keys from both objects, where entries present in the right object are replaced. Note that the casing used by right will be used.

mergeLeftIgnoreCase

  • mergeLeftIgnoreCase<LeftT, RightT>(left?: LeftT, right?: RightT): Record<string, any>
  • Create an object by merging the right object into a shallow copy of the left object ignoring casing, but keeping the right casing. Only keys present in the left object will be present in the merged object.

    Type parameters

    • LeftT: Record<string, any>

    • RightT: Record<string, any>

    Parameters

    • Default value left: LeftT = {} as LeftT

      Object to merge into. They keys of this object will be present in the returned object.

    • Default value right: RightT = {} as RightT

      Object to merge. Only keys in left will be considered for merging.

    Returns Record<string, any>

    • An object containing all keys from the left object, where entries present in the right object are replaced. Note that the casing used by right will be used.

Const mergeSome

  • mergeSome(a: Record<string, any>, b?: Record<string, any>): Record<string, any>
  • Merges the two objects, if second object is neither null nor undefined. If a key exists on a and b the value from b is taken

    deprecated

    This will be removed in version 2.0 of the SDK.

    Parameters

    • a: Record<string, any>

      The object to merge into.

    • Optional b: Record<string, any>

      The object which to merge into a.

    Returns Record<string, any>

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

muteLoggers

  • muteLoggers(): void

Const pick

  • pick<T>(keys: string[], obj: T): Partial<T>
  • Create a shallow copy of the given object, that contains the given keys. Non existing keys in the source object are ignored.

    Type parameters

    • T

    Parameters

    • keys: string[]

      properties to be selected

    • obj: T

      object from which the values are taken

    Returns Partial<T>

    an object with the selected keys and corresponding values.

pickIgnoreCase

  • pickIgnoreCase<T>(obj?: T, ...keys: string[]): Partial<Pick<T, typeof keys[number]>>
  • Create a shallow copy of the given object, that contains the given keys, independent of casing. Non existing keys in the source object are ignored.

    Type parameters

    • T: Record<string, any>

    Parameters

    • Default value obj: T = {} as T

      Object to pick the given key from.

    • Rest ...keys: string[]

      Keys of the pair to be picked.

    Returns Partial<Pick<T, typeof keys[number]>>

    • An object containing the given key-value pairs in its original case or an empty object if none of them are found.

pickNonNullish

  • pickNonNullish<T>(obj?: T): Partial<T>
  • Create a shallow copy of the given object, that contains all entries with non-nullish values.

    Type parameters

    • T: Record<string, any>

    Parameters

    • Default value obj: T = {} as T

      An object to pick from.

    Returns Partial<T>

    • A filtered object containing only keys with non-nullish values.

pickValueIgnoreCase

  • pickValueIgnoreCase<T>(obj?: T, key: string): any | undefined
  • Returns the value of an object based on the given key, independent of casing.

    Type parameters

    • T: Record<string, any>

    Parameters

    • Default value obj: T = {} as T

      Object to be searched for the given key.

    • key: string

      Key of the value to pick.

    Returns any | undefined

    The value of for the given key or undefined if not available.

propertyExists

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

    Parameters

    • obj: Record<string, any>

      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: Record<string, string>, obj: Record<string, any>): Record<string, 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: Record<string, string>

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

    • obj: Record<string, any>

      The input object.

    Returns Record<string, any>

    An object with renamed keys.

setGlobalLogLevel

  • setGlobalLogLevel(level: LogLevel): void
  • Change the global log level of the container which will set default level for all active loggers. E. g., to set the global log level call setGlobalLogLevel('debug').

    Parameters

    Returns void

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. Use an empty string '' as level to unset context level.

    • 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

splitInChunks

  • splitInChunks<T>(arr: T[], chunkSize: number): T[][]
  • Split the given array in chunks

    Type parameters

    • T

    Parameters

    • arr: T[]

      Array to be splitted. The last aray could be shorter.

    • chunkSize: number

      Size of the chunks

    Returns T[][]

    Array with arrays of chunks size.

toSanitizedObject

  • toSanitizedObject(key: string, value: any): Record<string, any>
  • Create an object based on the given key and value if neither key nor value are nullish.

    Parameters

    • key: string

      Name of the header.

    • value: any

      Value of the header.

    Returns Record<string, any>

    • An object containing the given key and value of an empty object.

unique

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

    Type parameters

    • T

    Parameters

    • arr: T[]

      Array that might contain duplicates

    Returns T[]

    Array of unique items

unmuteLoggers

  • unmuteLoggers(): void

variadicArgumentToArray

  • variadicArgumentToArray<T>(firstOrArray: undefined | T | T[], rest: T[]): T[]
  • We want to provide methods which accept a variable single number of elements and arrays. The overloaded signature to achieve this is: function doSomething(array: T[]) function doSomething(...varArgs: T[]) functiondoSomething(first: undefined | T | T[], ...rest: T[]) { //implementation } This wrapper methods makes it easy build an array from the input.

    Type parameters

    • T

    Parameters

    • firstOrArray: undefined | T | T[]

      Either an array, the first element of the var args or undefined if no argument was given.

    • rest: T[]

      Second to last element if var args were used, empty array if the frist argument is an array.

    Returns T[]

    Array from the input or empty array if no input was given.