aura-bot-library-util utility

aura-bot-library-util utility contains different utility files for aura-bot libraries

Introduction

aura-bot-library-util utility is an NPM library with utility functions provided by the Aura Bot Global Team to make it easier the development of dialogs in aura-bot.

Find more information in the Github repository: https://github.com/Telefonica/aura-common-utilities/tree/master/packages/aura-bot-utilities/src/aura-bot-library-util/

This library only contains utilities used in the dialogs, not needed by the bot itself.

To use it, just define the dependency with @telefonica/aura-bot-library-util in your package.json file. It is published as a private library in NPM, so request a valid NPM token to access it.

The utility files included in aura-bot-library-util utility are described in the following sections.

CurrencyUtils

aura-bot-library-util/currency-util.ts

getLocalizedCurrency

It returns money amounts formatted with country specific settings.

param type description mandatory
locale string Country locale code yes
amount number Total amount to be formatted yes
currency string Country currency code yes

    const amount: string = getLocalizedCurrency('es-es', 460.56, 'EUR');

    /* 460.56 € */

    const amount: string = getLocalizedCurrency('es-uy', 460.56, 'UYU');

    /* $ 461 */

Datautils

aura-bot-library-util/data-unit-util.ts

getDataAndUnit

It returns converted internet data amount and unit from bytes quantity, following the country specific settings.

param type description mandatory
content TurnContext Step context yes
configuration Configuration Dialog config variables yes
data number Data amount yes
forcePoint boolean It indicates if the decimals will be separated by points no

    const [dataQt, dataUnit] = getDataAndUnit(context, config, 1536)
    const [dataQt, dataUnit] = getDataAndUnit(context, config, 1536, true)

    /*
     * Result depending on AURA_DEFAULT_LOCALE env var
     * pt-br - ['1,5', 'GB']
     * en-gb - ['1.50', 'GB']
    */

LocaleUtils

aura-bot-library-util/locale-util.ts

getLiteral

This intermediate method generates a getText function ready to receive resources keys and sequential params.

param type description mandatory
context TurnContext step context yes
library string libraryName no

    /* If we need to convert only one text in function scope, we can use it as one line function */

    const text: string = getLiteral(context, 'services')('services.find.moreinfo', param1, param2);
    const text: string = getLiteral(context)('services:services.find.moreinfo', param1, param2);

    /* When we need to convert several texts in function scope for the same library,
    we can preassign result function to variable and proceed all along dialog step */

    const getServicesText: Function = getLiteral(context, 'services');

    const text: string = getServicesText('services.find.moreinfo', param1, param2);

    /* if we need to convert several texts in function scope for several libraries */

    const getText: Function = getLiteral(context);

    const text: string = getText('services:services.find.moreinfo', param1, param2);
    const errorText: string = getText('errors:error.notFound');

getTextByKeys

Factory function used mainly in graphs to retrieve converted text objects, avoiding redundancy.

param type description mandatory
context TurnContext step context yes
libraryName string libraryName yes

    const getGraphText: Function = getTextByKeys(context, 'graphics');

    const texts: any = getGraphTexts(['of', 'remaining'], { unit: 'data.gb' })

    /* Output
        {
            of: 'graphics:of', // converted text,
            remaining: 'graphics:remaining', // converted text,
            unit: graphics:data.gb, // converted text
        }
    */

withLocale

It encapsulates all data we need to call LocaleManager instance getText method.

param type description mandatory
context TurnContext step context yes
fn Function function to be executed at the end yes
library string libraryName no

For instance, getLiteral function passes an inline arrow function to simply receive the params that the result function was invoked with:


    /**
     * handy method to retrieve text.
     *
     * @param  {TurnContext} context The dialog step context.
     * @param  {string} libraryName? Library name.
     */
    export function getLiteral(context: TurnContext, libraryName?: string) {
        return withLocale(
            context,
            ({ getText, library }: any, literal: string, ...args: any[]) => getText(`${library ? library + ':' : ''}${literal}`, args),
            libraryName
        );
    }

This way, we can compose any method that fits our dialog text composition specific needs. A trivial working code sample could be:


    const _getText: Function = withLocale(stepContext.context, intermediateFunc)

    function intermediateFunc({ getText }, obj: any, params: string[], isError?: boolean) {
        const finalTextKey: string = isError ? obj.error : obj.text;
        return getText(finalTextKey, params);
    }

    const obj = {
        text: 'services:services.some.text',
        error: 'errors:error.message.error'
    }

    const text: string = _getText(obj, ['first', 'second']);
    const errorText: string = _getText(obj, [], true);

getErrorMessage

It composes a full error message with fallback text when required.

param type description mandatory
context TurnContext step context yes
statusCode number request code, if existing nullable
objErr StatusCodeMessagesMap Custom error messages no
    export interface StatusCodeMessagesMap {
        default: string;
        code400?: string;
        code404?: string;
    }
    try {
        //Do stuff
    } catch (error) {
        const messageMap: StatusCodeMessageMap = {
            default: 'services:services.custom.error',
            code400: 'services:services.error.badRequest',
            code404: 'services:services.error.notFound'
        }

        const errorMessage: string = getErrorMessage(stepContext.context, error.code, messageMap)
    }

sendLoggerErrorAndActivity

It sends full logged error message activity.

param type description mandatory
context TurnContext step context yes
logger any log function yes
objErr StatusCodeMessagesMap Custom error messages yes
dialogId string Current dialog ID yes
error any error to print yes
    try {
        /* [...] */
    }  catch (error ) {

        const messageMap: StatusCodeMessageMap = {
            default: 'services:services.custom.error',
            code400: 'services:services.error.badRequest',
            code404: 'services:services.error.notFound'
        }


        sendLoggerErrorAndActivity(
            context,
            this.logger,
            messageMap,
            ServicesFindDialog.id,
            error
        )
    }

LibraryUtil

aura-bot-library-util/library-util.ts

excludeDialogs

It excludes dialogs provided in an array.

param type description mandatory
dialogNames string[] Array with dialog’s ids yes
options any Options to customize function behavior yes
excludeDialogs(dialogNames: string[], options: any);

readLocaleFolder

Ir returns an object with locale name as key and file content as value.

param type description mandatory
localePath string localePath Base path where locale files are looked for yes
readLocaleFolder(localePath: string);

readEnv

It returns an object with env variables from current environment.

param type description mandatory
configuration any Object with configuration information yes
envPath string Path pointing to environment configuration yes
readEnv(configuration: any, envPath: string);

readDialogConfig

It returns an object with dialog config from current environment.

param type description mandatory
configuration any Object with configuration information yes
configPath string Path pointing to dialog configuration yes
readDialogConfig(configuration: any, configPath: string);

replaceToDialogByIntent

Given an intent, it replaces the current dialog by the intent that matches with it. This method triggers the main dialog and keeps the context-filter functionality in the replaced one.

param type description mandatory
stepContext WaterfallStepContext step context yes
intent string intent which the dialog will be triggered yes
await replaceToDialogByIntent(stepContext: WaterfallStepContext, intent: string);

generateSasUrl

It generates and returns the URL of the blob resource, applying expiration.

param type description mandatory
fileName string Blob file name yes
remoteContainerPath string Full container’s path yes
expiration number Expiration time in minutes no
configuration Configuration Environment configuration yes
correlator string Correlator no
await generateSasUrl(fileName: string, remoteContainerPath: string,
    configuration: Configuration, corr?: string, expiration?: number);

uploadFileUrl

It uploads a file to Azure Storage from an URL.

param type description mandatory
sourceUrlFile string URL that contains the file yes
remoteFilePath string Blob remote path yes
configuration Configuration Environment configuration yes
correlator string Correlator no
containerName string Storage container name no
await uploadFileUrl(sourceUrlFile: string, remoteFilePath: string,
    configuration: Configuration, corr?: string, containerName?: string) ;

ResourcesUtils

aura-bot-library-util/resources-util.ts

getImageUrl

It intercalates supported resolution folder path into image path, following channel image resolution settings.

param type description mandatory
context TurnContext step context yes
libraryName string Library proper name yes
url string Full path of the image default version in the library root folder yes
configuration Configuration Env variables yes
    // Current supported resolutions.
    enum SupportedResolutions {
        HDPI = 'hdpi',
        XHDPI = 'xhdpi',
        XXHDPI = 'xxhdpi',
        XXXHDPI = 'xxxhdpi'
    }

    // Taking channelData imageSettings resolution == xxxhdpi

    getImageUrl(context, 'services', 'images/default/imageName.png', configuration);

    // https://<storageUrl>/libraries/services/images/xxxhdpi/imageName.png?<params>

getResourcePath

It gets the whole resource path uploaded to blob-storage, that is accessible, to be included in cards.

param type description mandatory
configuration any Env variables yes
libraryName string Library proper name yes
baseFilePath string Base file access path yes
const uri: string = DialogUtils.getResourcePath('generic', resource, this.configuration);