Skip to content
lokalisePublic

About

Core libraries for Node.js backend services

Topics

Resources

Code of conduct

Contributing

Stars

7 stars

Watchers

18 watching

Forks

Repository files navigation

node-core 🧬

Core libraries for Node.js backend services.

See docs for further instructions on how to use.

Default Logging Configuration

Warning

The logging exports are deprecated in favour of @lokalise/observability and will be removed in a future major version. See Migrating to @lokalise/observability.

The library provides methods to resolve the default logging configuration. Public methods available are:

  • resolveLoggerConfiguration(), which accepts as parameter an appConfig, defined by the logLevel and the nodeEnv. If the environment is production, the output will be logged in JSON format to be friendly with any data storage. Otherwise, the output will be logged with coloring and formatting to be visible for debugging purposes and help developers.

    The method returns a logger configuration that should be used with pino library as in the following example:

    const loggerConfig = resolveLoggerConfiguration({
      logLevel: 'warn',
      nodeEnv: 'production',
      redact: {
        paths: ['path1', 'path2'],
      },
    })
    
    const logger = pino(loggerConfig)
  • resolveMonorepoLoggerConfiguration(), which accepts as parameter an appConfig, defined by the logLevel and the nodeEnv. It mostly behaves the same as resolveLoggerConfiguration, with the exception of execution in development environments. Since monorepo services are usually ran concurrently, logs from stdout aren't easily accessible. For this reason this logging configuration writes development logs into files.

    The method returns a logger configuration that should be used with pino library as in the following example:

    const loggerConfig = resolveMonorepoLoggerConfiguration({
      logLevel: 'warn',
      nodeEnv: 'production',
      append: false,
      // targetFile: './logs/service.log' -- optional parameter, you can specify exact path for writing logs
    })
    
    const logger = pino(loggerConfig)

ConfigScope

Warning

ConfigScope is deprecated in favour of envase and will be removed in a future major version.

ConfigScope is a class that provides a way to encapsulate a single config source (e. g. process.env) and produce a set of values out of it, defining constraints and transformations for them.

Once the class is instantiated, you can leverage the following ConfigScope methods:

Configuration Parameters by zod schema

  • getBySchema(), uses zod schema to validate configuration parameter, the returned type is inferred from the schema
    • param, the configuration parameter name;
    • schema, zod schema to use for parsing and validation;

Note: Starting from version 14, the library requires Zod v4 API usage, to continue using Zod v3 API, please use version 13 of the library.

Mandatory Configuration Parameters

  • getMandatory(), returns the value of a mandatory configuration parameter. If the value is missing, an InternalError is thrown. Parameters are:
    • param, the configuration parameter name;
  • getMandatoryInteger(), returns the value of a mandatory configuration parameter and validates that it is an integer number. If the value is missing or is not an integer, an InternalError is thrown. Parameters are:
    • param, the configuration parameter name;
  • getMandatoryNumber(), returns the value of a mandatory configuration parameter and validates that it is a number. If the value is missing or is not a number, an InternalError is thrown. Parameters are:
    • param, the configuration parameter name;
  • getMandatoryOneOf(), returns the value a mandatory configuration parameter and validates that it is one of the supported values. If the value is missing or is not supported, an InternalError is thrown. The method also serves as a type guard, narrowing the type of the passed value down to one of the supported options. Parameters are:
    • param, the configuration parameter name;
    • supportedValues;
  • getMandatoryValidatedInteger(), similar to getMandatoryInteger(), but also takes a validator in input and will throw an InternalError if the number is not valid. See Validators and Transformers for more information. Parameters are:
    • param, the configuration parameter name;
    • validator;
  • getMandatoryValidatedNumber(), similar to getMandatoryNumber(), but also takes a validator in input and will throw an InternalError if the number is not valid. See Validators and Transformers for more information. Parameters are:
    • param, the configuration parameter name;
    • validator;
  • getMandatoryTransformed(), calls getMandatory() and returns the result of the transformer function applied to the configuration parameter value. See Validators and Transformers for more information. Parameters are:
    • param, the configuration parameter name;
    • transformer.

Optional Configuration Parameters

  • getOptionalNullable(), returns the value of an optional configuration parameter. If the value is missing, it is set to the provided default value.Parameters are:
    • param, the configuration parameter name;
    • defaultValue, which can be nullable;
  • getOptional(), similar to getOptionalNullable(), but defaultValue cannot be nullable. The return value is always a string;
  • getOptionalNullableInteger(), returns the value of an optional configuration parameter and validates that it is an integer number. If the value is missing, it is set to the provided default value. If it is not a number, an InternalError is thrown. Parameters are:
    • param, the configuration parameter name;
    • defaultValue, which can be nullable;
  • getOptionalNullableNumber(), returns the value of an optional configuration parameter and validates that it is a number. If the value is missing, it is set to the provided default value. If it is not a number, an InternalError is thrown. Parameters are:
    • param, the configuration parameter name;
    • defaultValue, which can be nullable;
  • getOptionalInteger, similar to getOptionalNullableInteger(), but defaultValue cannot be nullable. The return value is always a number;
  • getOptionalNumber, similar to getOptionalNullableNumber(), but defaultValue cannot be nullable. The return value is always a number;
  • getOptionalValidated(), similar to getOptional(), but also takes a validator in input and will throw an InternalError if the value is not valid. See Validators and Transformers for more information. Parameters are:
    • param, the configuration parameter name;
    • validator;
  • getOptionalValidatedInteger(), similar to getOptionalValidated(), but expects and returns an integer number instead. See Validators and Transformers for more information. Parameters are:
    • param, the configuration parameter name;
    • validator;
  • getOptionalValidatedNumber(), similar to getOptionalValidated(), but expects and returns number instead. See Validators and Transformers for more information. Parameters are:
    • param, the configuration parameter name;
    • validator;
  • getOptionalTransformed(), similar to getOptional(), but also takes a transformer in input and the result of the transformer function applied to the configuration parameter value. See Validators and Transformers for more information. Parameters are:
    • param, the configuration parameter name;
    • defaultValue,
    • transformer;
  • getOptionalBoolean(), returns the value of an optional configuration parameter and validates that it is a boolean. It the value is missing, it is assigned the defaultValue. If it is not a boolean, an InternalError is thrown. Parameters are:
    • param, the configuration parameter name;
    • defaultValue.
  • getOptionalOneOf(), returns the value of an optional configuration parameter, if the value is missing, it falls back to the specified default value, and validates that it is one of the supported values. If the value is not supported, an InternalError is thrown. Parameters are:
    • param, the configuration parameter name;
    • defaultValue
    • supportedValues;

Environment Configuration Parameter

  • isProduction(), returns true if the environment is production;
  • isDevelopment(), returns true if the environment is not production;
  • isTest(), returns true if the environment is test.

Validators and Transformers

Ad-hoc validators and transformers can be built leveraging the EnvValueValidator and the EnvValueTransformer types exposed by the library. Alternatively, the following validators and transformers are already provided out of the box:

Validators

  • createRangeValidator(), which accepts greaterOrEqualThan and lessOrEqualThan and validates that a numeric value ranges between those numbers.

Transformers

  • ensureClosingSlashTransformer(), which accepts a value as parameter, that can be a string or nullable, and adds a closing slash if it is missing and the value is defined.

Error Handling

The library provides classes and methods for error handling.

Global Error Handler

Warning

The global error handler, ErrorReport, ErrorReporter and ErrorResolver are deprecated in favour of @lokalise/observability and will be removed in a future major version. See Migrating to @lokalise/observability.

Public methods to leverage a global error handler are provided to be used when the process is run outside of the context of the request (e. g. in a queue where no one would catch an error if thrown):

  • resolveGlobalErrorLogObject(), which accepts err and optionally correlationID as parameters and converts the plain error into a serializable object. If the error is not a built-in Error type and doesn't have any message, a fixed string is returned instead;
  • executeAndHandleGlobalErrors(), which accepts the operation parameter and will return the result of executing such operation. If an error is thrown during the execution of the operation, resolveGlobalErrorLogObject() is called to log the error and the process is terminated;
  • executeAsyncAndHandleGlobalErrors(), which accepts operation and optionally stopOnError as parameters and will return the result of executing such operation asynchronously. If an error is thrown during the execution of the operation, resolveGlobalErrorLogObject() is called to log the error and the process is terminated only if stopOnError is true. stopOnError defaults to true if not provided.

Errors

Warning

The error classes and type guards below are deprecated in favour of @lokalise/errors and will be removed in a future major version. Use InternalError.from() for internal errors, and definePublicError() with PublicError.from() for public errors.

Replacements for the type guards depend on which package created the error. isInstance() from @lokalise/errors does not match errors created by node-core, so keep using instanceof with the node-core class until those errors are migrated:

Deprecated guard Errors created by node-core Errors created by @lokalise/errors
isInternalError(error) error instanceof InternalError InternalError.isInstance(error)
isPublicNonRecoverableError(error) error instanceof PublicNonRecoverableError PublicError.isInstance(error)
isEntityGoneError(error) error instanceof EntityGoneError YourGoneError.isInstance(error), where YourGoneError is your own class built with PublicError.from()

isEntityGoneError matches any PublicNonRecoverableError with httpStatusCode 410, while instanceof EntityGoneError matches only that class. If you create 410 errors directly with new PublicNonRecoverableError({ httpStatusCode: 410, ... }), check error instanceof PublicNonRecoverableError && error.httpStatusCode === 410 instead.

The library exposes classes for the following errors:

  • InternalError, which issues a 500 status code and is not exposed in the global error handler. It expects the following parameters:
    • message;
    • errorCode;
    • details – (optional);
    • cause – (optional).
  • PublicNonRecoverableError, which issues the HTTP status code provided and signals that the user did something wrong, hence the error is returned to the consumer of the API. It expects the following parameters:
    • message;
    • errorCode;
    • details – (optional);
    • cause – (optional);
    • httpStatusCode – (optional). Defaults to 500;

Either

Warning

Either, DefiniteEither, success, failure, isSuccess and isFailure are deprecated in favour of the same exports from @lokalise/universal-ts-utils and will be removed in a future major version.

The library provides the type Either for error handling in the functional paradigm. The two possible values are:

  • result is defined, error is undefined;
  • error is defined, result is undefined.

It's up to the caller of the function to handle the received error or throw an error.

Read this article for more information on how Either works and its benefits.

Additionally, DefiniteEither is also provided. It is a variation of the aforementioned Either, which may or may not have error set, but always has result.

waitAndRetry

Warning

waitAndRetry is deprecated in favour of the same export from @lokalise/universal-ts-utils and will be removed in a future major version.

There is helper function available for writing event-driven assertions in automated tests, which rely on something eventually happening:

import { waitAndRetry } from '@lokalise/node-core'

const result = await waitAndRetry(
  () => {
    return someEventEmitter.emittedEvents.length > 0
  },
  20, // sleepTime between attempts
  30, // maxRetryCount before timeout
)

expect(result).toBe(false) // resolves to what the last attempt has returned
expect(someEventEmitter.emittedEvents.length).toBe(1)

Encryption

Warning

EncryptionUtility is deprecated in favour of the same export from @lokalise/crypto and will be removed in a future major version. It decrypts values encrypted by this one.

Hashing

Warning

generateHash, generateHmac, HashAlgorithm and HashEncoding are deprecated in favour of calculateHash, calculateHmac, HashAlgorithm and HashEncoding from @lokalise/crypto and will be removed in a future major version. HashAlgorithm and HashEncoding are const objects there, not enums.

  • HashUtils - utils for hashing using sha256/sha512 algorithms

Checksum

Warning

The checksum utils are deprecated in favour of @lokalise/crypto and will be removed in a future major version. Replace generateChecksumForBufferOrString with calculateChecksum and generateChecksumForReadable with calculateStreamChecksum. Replace generateChecksumForObject(object) with calculateChecksum(JSON.stringify(object)) to keep the same checksums; calculateChecksum(object) ignores key order, but its checksums differ.

  • ChecksumUtils - utils for insecure hashing using the MD5 algorithm

Streams

  • StreamUtils - utils for temporary persisting of streams for length calculation and reuse
  • streamToBuffer - utility for converting a stream to a buffer

Observability

Warning

The exports in this section are deprecated in favour of the same exports from @lokalise/observability and will be removed in a future major version.

The library provides utilities for transaction observability management through the TransactionObservabilityManager interface.

TransactionObservabilityManager

An interface for tracking background transactions with the following methods:

  • start(transactionName, uniqueTransactionKey) - Creates and starts a background transaction
  • startWithGroup(transactionName, uniqueTransactionKey, transactionGroup) - Creates and starts a background transaction related to a specified group
  • stop(uniqueTransactionKey, wasSuccessful?) - Ends the transaction
  • addCustomAttributes(uniqueTransactionKey, atts) - Adds custom attributes to the current transaction
  • runInSpanContext(uniqueTransactionKey, fn) (optional) - Runs fn with the transaction set as the active one

start and stop are two separate calls and cannot express a scope, so implementations able to propagate context opt in by providing runInSpanContext. Consumers should not call it directly - use runInTransactionContext below, which handles managers that do not support it.

Implementations of runInSpanContext must call fn exactly once, return its value and let the errors it throws through unchanged, because callers put their business logic in fn and cannot retry it. When fn returns a promise, they must also keep the context active for the lifetime of that promise, which needs AsyncLocalStorage or an equivalent: activating the span and restoring the previous one in a synchronous finally restores it at the first await, leaving everything after it detached again.

runInTransactionContext

Runs a function within the observability context of an already started transaction, so that work performed inside it (spans, queries, outgoing calls) is recorded as part of that transaction instead of as detached top-level work. Runs the function directly when the manager is missing or cannot propagate context, so a manager without context propagation costs the caller nothing. When the manager can propagate context, it is the one that invokes the function, and its errors reach the caller: a manager breaking the contract above can skip the work or fail the caller.

import { runInTransactionContext } from '@lokalise/node-core'

observabilityManager.start('processOrder', 'order-123')
let wasSuccessful = false
try {
  // spans created while processing become part of the `order-123` transaction
  await runInTransactionContext(observabilityManager, 'order-123', () => processOrder(order))
  wasSuccessful = true
} finally {
  observabilityManager.stop('order-123', wasSuccessful)
}

Prefer it over an inline manager.runInSpanContext?.(key, fn) ?? fn(), which executes fn twice whenever it legitimately returns undefined or null.

MultiTransactionObservabilityManager

Groups multiple TransactionObservabilityManager instances into one to facilitate tracking transactions across multiple observability tools.

import { MultiTransactionObservabilityManager } from '@lokalise/node-core'

const multiManager = new MultiTransactionObservabilityManager([
  newRelicManager,
  datadogManager,
])

multiManager.start('processOrder', 'order-123')

runInSpanContext nests the contexts of every wrapped manager able to propagate one, so the function runs within all of them; managers without context propagation are skipped. It is only present when at least one wrapped manager can propagate context, so checking for it answers whether the wrapped managers will connect the traces.

NoopObservabilityManager

A no-operation implementation of TransactionObservabilityManager. All methods are implemented and do nothing, except runInSpanContext, which runs the given function and returns its result without propagating any context. Use this when you need to satisfy a TransactionObservabilityManager dependency but don't want any actual observability tracking to occur.

import { NoopObservabilityManager } from '@lokalise/node-core'

const noopManager = new NoopObservabilityManager()
// Pass to any component requiring a TransactionObservabilityManager
const service = new MyService({ observabilityManager: noopManager })

Migrating to @lokalise/observability

Install the package and pino, which it takes as a peer dependency:

pnpm add @lokalise/observability pino
node-core @lokalise/observability
resolveLogger(config) resolveLogger(options). Same options except base, returns a CommonLogger
AppLoggerConfig ResolveLoggerOptions
resolveLoggerConfiguration, resolveMonorepoLogger, resolveMonorepoLoggerConfiguration, MonorepoAppLoggerConfig No replacement. Use resolveLogger
CommonLogger CommonLogger
logger.isLevelEnabled(level) isLevelEnabled(logger, level)
stringValueSerializer stringifyForLog
globalLogger globalLogger
resolveGlobalErrorLogObject(err) logger.error(err) or logger.error({ err })
executeAndHandleGlobalErrors, executeAsyncAndHandleGlobalErrors runOrExit
executeSettleAllAndHandleGlobalErrors(promises) runOrExit(() => Promise.all(promises))
ErrorReport, ErrorReporter ErrorReport, ErrorReporter
ErrorResolver No replacement
TransactionObservabilityManager, MultiTransactionObservabilityManager, NoopObservabilityManager, runInTransactionContext Same names

What behaves differently:

  • Errors are logged under err. The logger from resolveLogger serializes an Error under err with its type, message, stack and causes, each cause with its own fields. An Error under error is logged as {}, so replace logger.error({ error }) and objects built with resolveGlobalErrorLogObject with logger.error(err) or logger.error({ err, 'x-request-id': requestId }).
  • CommonLogger is narrower. It has the log methods, level and child, so app.log and request.log fit without an as CommonLogger. msgPrefix and isLevelEnabled are gone.
  • runOrExit handles sync and async operations. It returns the result, or logs the error with globalLogger and exits with code 1. There's no stopOnError: false. Catch and log the error where the process should keep running. With Promise.all, only the first rejection is logged.
  • stringifyForLog writes plain JSON. It doesn't wrap strings in extra quotes, so update Datadog queries that match them. Errors, circular references and functions come out readable, and truncated text ends with a marker.
import { resolveLogger, runOrExit } from '@lokalise/observability'

const config = runOrExit(() => getConfig())
const logger = resolveLogger({ logLevel: config.logLevel, nodeEnv: config.nodeEnv })

try {
  await importFile(file)
} catch (err) {
  logger.error({ err, fileId: file.id }, 'Import failed')
}

About

Core libraries for Node.js backend services

Topics

Resources

Code of conduct

Contributing

Stars

7 stars

Watchers

18 watching

Forks

Releases

Packages

Used by

Contributors

Languages