Options
All
  • Public
  • Public/Protected
  • All
Menu

SAP Cloud SDK for JavaScript Logo

Version 2 Release

The SAP Cloud SDK has released version 2. Check the upgrade guide for more details. Make sure you understand our release policy.

@sap-cloud-sdk/util

This package 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 Business Technology 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');

Support

The recommended way to get in touch with us is to create an issue in our github repository. Select the issue category Bug, Feature or Question depending on the nature of your request. We try to provide fixes, features and answers as soon as possible.

Contribute

If you would like to contribute to the SAP Cloud SDK, please make yourself familiar with our contributing guidelines and follow the given instructions.

Links



License

The SAP Cloud SDK is released under the Apache License Version 2.0.

Index

Type aliases

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

Npm log levels used for the SAP Cloud SDK logger.

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

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

Type parameters

  • T

ODataVersion: "v2" | "v4"

Denotes the OData version.

Variables

VALUE_IS_UNDEFINED: "VALUE_IS_UNDEFINED" = 'VALUE_IS_UNDEFINED'
cloudSdkExceptionLogger: Logger

Default logger for the SAP Cloud SDK for unhandled exceptions.

kibana: Format

Format for logging in Kibana.

local: Format

Format for local logging.

unixEOL: "\n" = "\n"

Within all files generated by the SDK we use the unix style end of line delimiter. We do not consider if the generator is executed on windows or unix systems. It will always be \n to have consistent clients between operating systems.

webEOL: "\r\n" = "\r\n"

For request payloads, etc., it is convention to use the \r\n new line.

Functions

  • assoc<T>(key: string, value: any, obj: T): T & {}
  • 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 & {}

    the object with the key value pair added

  • assocSome<T>(key: string, value?: any): (obj: T) => T
  • deprecated

    This will be removed in version 2.0 of the SDK. 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 being added.

    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 (obj: T) => T

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

      • (obj: T): T
      • Parameters

        • obj: T

        Returns T

  • asyncPipe(...fns: CallableFunction[]): (start: any) => Promise<any>
  • Same as pipe but for asynchronous functions: asyncPipe(func1, 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: CallableFunction[]

      A list of asynchronous functions to be executed in sequence.

    Returns (start: any) => Promise<any>

    The return value of the last function in the list.

      • (start: any): Promise<any>
      • Parameters

        • start: any

        Returns Promise<any>

  • camelCase(str: string): string
  • Convert a string to camelCase. This format used e. g. for properties on entity class instances.

    Parameters

    • str: string

      The string to be transformed.

    Returns string

    The transformed string.

  • 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'

  • checkUrlExists(url: string): Promise<number>
  • Checks whether a URL is existing via a head request.

    Parameters

    • url: string

      URL to be checked

    Returns Promise<number>

    promise - resolves if the URL exists

  • codeBlock(strings: TemplateStringsArray, ...args: any[]): string
  • experimental

    This API is experimental and might change in newer versions. Use with caution. Transform strings and arguments to a string formatted as a code block, keeping the indentation of sub code blocks. Use in tagged templates, e. g.:

    codeBlock`Code with ${arguments} and more code;`
    

    Parameters

    • strings: TemplateStringsArray

      Strings in the tagged template. In the example above that would be ['Code with ', ' and more code;'].

    • Rest ...args: any[]

      Arguments in the tagged template. In the example above that would be the resolved value for arguments;

    Returns string

    A string formatted as code block.

  • 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(): void
  • Disable logging of exceptions. Enabled by default.

    Returns void

  • documentationBlock(strings: TemplateStringsArray, ...args: string[]): string
  • experimental

    This API is experimental and might change in newer versions. Use with caution. Transform strings and arguments to a string formatted as a documentation block. The formatting is block like so no leading or trailing spaces. New lines in the beginning and end are also removed. Use in tagged templates, e. g.:

    documentationBlock`Docs with ${arguments} and more content;`
    

    Parameters

    • strings: TemplateStringsArray

      Strings in the tagged template. In the example above that would be ['Docs with ', ' and more content;'].

    • Rest ...args: string[]

      Arguments in the tagged template. In the example above that would be the resolved value for arguments;

    Returns string

    A string formatted as documentation block.

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

    Returns void

  • encodeBase64(str: string): string
  • Encode a string to a base64 encoded string.

    Parameters

    • str: string

      String to encode.

    Returns string

    Base64 encoded string.

  • equal<T>(item1: T, item2: T): boolean
  • equalArrays<T>(arr1: T[], arr2: T[]): boolean
  • equalObjects(obj1: Record<string, any>, obj2: Record<string, any>): boolean
  • errorWithCause(message: string, cause: Error): Error
  • deprecated

    Since v1.34.0. Use ErrorWithCause instead. Creates a new Error and adds the stack trace of the original error to the stack trace of the new one.

    Parameters

    • message: string

      Error message.

    • cause: Error

      Original error, causing the new error.

    Returns Error

    A new error with the given cause.

  • exclude<T>(keys: string[], obj: T): Partial<T>
  • Create a shallow copy of the given object, that does not contain 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.

  • filterDuplicates<T>(arr: T[], comparator?: (left: T, right: T) => boolean): T[]
  • Filter an array by removing duplicates and keeping the left most occurrence. By default this compares by identity.

    Type parameters

    • T

    Parameters

    • arr: T[]

      Array to remove duplicates from.

    • comparator: (left: T, right: T) => boolean = ...

      Optional comparator function, indicating whether two items are equal and therefore handled as duplicates. Defaults to identity.

        • (left: T, right: T): boolean
        • Parameters

          • left: T
          • right: T

          Returns boolean

    Returns T[]

    A filtered array containing no duplicates.

  • filterDuplicatesRight<T>(arr: T[], comparator?: (left: T, right: T) => boolean): T[]
  • Filter an array by removing duplicates and keeping the right most occurrence. By default this compares by identity.

    Type parameters

    • T

    Parameters

    • arr: T[]

      Array to remove duplicates from.

    • comparator: (left: T, right: T) => boolean = ...

      Optional comparator function, indicating whether two items are equal and therefore handled as duplicates. Defaults to identity.

        • (left: T, right: T): boolean
        • Parameters

          • left: T
          • right: T

          Returns boolean

    Returns T[]

    A filtered array containing no duplicates.

  • findProjectRoot(path: string, lastPath?: string): string
  • finishAll(promises: Promise<any>[], errorMessage?: string): Promise<void>
  • Await all promises and resolve if non of them failed. Reject if at least one of them was rejected, but only once all of them are finished. Throws an error consisting of a list of reasons.

    Parameters

    • promises: Promise<any>[]

      Promises to settle.

    • Optional errorMessage: string

      Message to use as introductory text of the error if an error occurs.

    Returns Promise<void>

  • 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<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.

  • 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 flattened array.

  • formatJson(json: any): string
  • Convert a JSON object to a string using formatting in line with the prettier with indentation and new line at the end.

    Parameters

    • json: any

      Object to be stringified

    Returns string

    The JSON object as string.

  • getGlobalLogLevel(): string | undefined
  • Returns string | undefined

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

    Parameters

    • Optional messageContext: string

      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

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

    Type parameters

    • T

    Parameters

    • argument: T

      Any object

    Returns T

    the given argument without doing something

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

    Parameters

    • val: any

      Value to check.

    Returns val is undefined | null

    true for null or undefined, false otherwise.

  • kebabCase(str: string): string
  • Convert a string to kebab case. This format is used e. g. for file names.

    Parameters

    • str: string

      The string to be transformed.

    Returns string

    The transformed string.

  • 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<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. Keys present both objects will be present in the merged object.

    Type parameters

    • LeftT: Record<string, any>

    • RightT: Record<string, any>

    Parameters

    • Optional left: LeftT

      Object to merge.

    • Optional right: RightT

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

    Returns Record<string, any>

    • 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<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

    • Optional left: LeftT

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

    • Optional right: 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.
  • mergeSome(a: Record<string, any>, b?: Record<string, any>): Record<string, any>
  • deprecated

    This will be removed in version 2.0 of the SDK. 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.

    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(): void
  • Mute all logger output created by the SAP Cloud SDK Logger. This also applies to future loggers created. Useful for tests.

    Returns void

  • partition<T>(arr: T[], condition: (item: T) => boolean): [T[], T[]]
  • Split an array into two based on a condition.

    Type parameters

    • T

    Parameters

    • arr: T[]

      Array to partition.

    • condition: (item: T) => boolean

      Function to determine to where to put each item.

        • (item: T): boolean
        • Parameters

          • item: T

          Returns boolean

    Returns [T[], T[]]

    A two dimensional array containing two arrays, where the first one includes all items where the given condition was met and the second one includes all items where it was not met.

  • pascalCase(str: string): string
  • Convert a string to pascal case. This format is used e. g. for types.

    Parameters

    • str: string

      The string to be transformed.

    Returns string

    The transformed string.

  • 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<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

    • Optional obj: 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<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

    • Optional obj: T

      An object to pick from.

    Returns Partial<T>

    • A filtered object containing only keys with non-nullish values.
  • pickValueIgnoreCase<T>(obj: undefined | 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

    • obj: undefined | 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(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.

  • readJSON(path: PathLike): {}
  • Read a JSON file from the file system.

    Parameters

    • path: PathLike

      The path to the JSON file.

    Returns {}

    An object parsed from the JSON file.

    • [key: string]: any
  • removeFileExtension(fileName: string): string
  • Remove file extension from a string, e.g. remove 'test.jpg' would return 'test'

    Parameters

    • fileName: string

      File name to remove the file extension from.

    Returns string

    File name without extension.

  • 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(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

    • level: LogLevel

      The log level to set the global log level to.

    Returns void

  • 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-accessor').

    Parameters

    • level: "" | LogLevel

      level to set the logger to. Use an empty string '' as level to unset context level.

    • Optional messageContextOrLogger: string | Logger

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

    Returns void

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

    Type parameters

    • T

    Parameters

    • arr: T[]

      Array to be split into chunks.

    • chunkSize: number

      Size of the chunks.

    Returns T[][]

    Two dimensional array with arrays of length chunkSize. The last subarray could be shorter.

  • titleFormat(str: string): string
  • Convert a string to a human readable format, e.g. it transforms to_BusinessPartner to To Business Partner.

    Parameters

    • str: string

      The string to be transformed.

    Returns string

    The transformed string.

  • 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.
  • trim(string: string): string
  • Remove whitespace from the left side of a string.

    Parameters

    • string: string

      String to trim.

    Returns string

    String without outer whitespace.

  • trimLeft(string: string): string
  • Remove whitespace from the left side of a string.

    Parameters

    • string: string

      String to trim.

    Returns string

    String without whitespace on the left side.

  • trimRight(string: string): string
  • Remove whitespace from the right side of a string.

    Parameters

    • string: string

      String to trim.

    Returns string

    String without whitespace on the right side.

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

    Type parameters

    • T

    Parameters

    • arr: T[]

      Array that might contain duplicates.

    Returns T[]

    Array of unique items.

  • unmuteLoggers(): void
  • Unmute all logger output created by the SAP Cloud SDK Logger. This also applies to future loggers created. Useful for tests.

    Returns void

  • upperCaseSnakeCase(str: string): string
  • Convert a string to the uppercase snake case. This format is used e. g. for static properties on entity classes.

    Parameters

    • str: string

      The string to be transformed.

    Returns string

    The input string in the case used by static methods on entity-classes.

  • 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[])
    function doSomething(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 first argument is an array.

    Returns T[]

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

  • zip<T>(left: T[], right: T[]): T[]
  • Merge two arrays by alternately adding inserting values from both arrays, starting from the left. For example: zip([1, 2], [3, 4, 5, 6]) results in [1, 3, 2, 4, 5, 6]

    Type parameters

    • T

    Parameters

    • left: T[]

      Array to start alternately merging from.

    • right: T[]

      Second array to merge.

    Returns T[]

    Zipped array.

    Copyright Ⓒ 2023 SAP SE or an SAP affiliate company. All rights reserved.