@elastic.io/component-commons-library

中文文档
4.0.3发布于 2026/08/14Apache-2.0TypeScriptCommonJS近 30 天下载 9700

Library for most common component development cases

原始使用文档
文档目录10 节
  1. Table of Contents
  2. Platform API Clients
  3. PlatformApiRestClient
  4. PlatformApiLogicClient
  5. JSON Schema Converter
  6. JSON Transformation
  7. Attachment Processor
  8. External API
  9. Environment variables
  10. Logger

component-commons-library

Table of Contents

Description

This library provides some of the most common component development functionality in a simple, reusable way.

To install, type

npm install @elastic.io/component-commons-library

Available Functions

Platform API Clients

A number of Platform API Client classes are available to use and extend them to create Clients for Platform API.

PlatformApiRestClient

PlatformApiRestClient class extends BasicAuthRestClient class. The method inside this class checks for the status code 200, if not, then throws an error. And also checks that the response came with the correct data in the JSON format and the other expected response headers.

constructor(emitter, cfg)

  • emitter - EIO emitting context.
  • cfg - configuration of EIO component object.
const Client = new PlatformApiRestClient(emitter, cfg);

PlatformApiLogicClient

PlatformApiLogicClient class extends PlatformApiRestClient class. Contains useful methods to manipulate flow's state to set it either to active running or to inactive stopped, searching flows, workspaces, credentials and more.

constructor(emitter, cfg)

  • emitter - EIO emitting context.
  • cfg - configuration of EIO component object.
const Client = new PlatformApiLogicClient(emitter, cfg);

List of methods

  • fetchAllFlowsForWorkspace(options) - Fetch all flows for a given workspace
  • fetchAllCredentialsForWorkspace(options) - Fetch all credentials for a given workspace
  • fetchAllSecretsForWorkspace - Fetch all secrets for a given workspace
  • fetchSecretById - Fetch secret by id for a given workspace
  • refreshTokenBySecretId - Refresh token by secret id for a given workspace
  • fetchComponentsAccessibleFromContract(options) - Fetch All Components Accessible From a Given Workspace
  • splitParallelization(maxParallelization, splitFactor) - Helping method to calculate right number of parallel calls
  • fetchFlowList(options) - Fetches a list of flows
  • fetchWorkspaceList(options) - Fetch a list of all workspaces across all contracts for a user
  • fetchWorkspaceId(workspaceUniqueCriteria) - Given a set of unique criteria, find the workspace that matches
  • removeNonWritableProperties(flow, includeDataSamples) - Given a flow, remove the properties of the flow that are regularly changed by the system such as last executed time
  • fetchFlowId(flowUniqueCriteria) - Fetch flow by it's unique criteria
  • fetchFlowById(id) - Fetch flow by it's id
  • fetchFlowByNameAndWorkspaceId(flowName, workspaceId) - Fetch flow by flow name and workspace id
  • changeFlowState(options) - Given a flow, change the flow to a given state (running, stopped, etc)
  • startFlow(flowId, options) - sets the flow to active running state
  • stopFlow(flowId, options) - sets the flow to inactive stopped state
  • hydrateFlow(options) - Hydrates the flow using removeNonWritableProperties method, but additionally enriches the flow with all data samples, credential names, command and component Id fields.

JSON Schema Converter

Contains tools for JSON metadata generation

  • convertJsonSchemaToEioSchema(keyToReturn, completeSchemaOriginal) - converts general JSON schema to platform-friendly JSON metadata
  • makeSchemaInline(json, availableSchemas) - replaces $ref recursively with full object description for provided json object using availableSchemas schemas map.

JSON Transformation

Contains functions to transform platform data that contains JSONata expressions

  • jsonataTransform(msg, cfg) - returns the msg.body with the JSONata expressions evaluated to values

Attachment Processor

The attachment processor function can be used to store attachments on the platform. It exposes the following functions

  • uploadAttachment(getAttachment, retryOptions, contentType), which will upload an attachment to the platform Maester storage and return the result object. Where:
    getAttachment - async function which returns stream
    retryOptions - (optional): parameters for retrying of upload attachment, if request failed. Parameters are retriesCount and requestTimeout(ms) contentType - (optional): Content-Type of attachment. By default Content-Type will be calculated automatically.
  • getAttachment(url, contentType), which will retrieve an attachment from steward or maester storage. To specify the storage - query parameter storage_type must be provided. To get items from maester storage - ?storage_type=maester should added to the url argument. By default attachments are retrieved from steward storage, so ?storage_type=steward is not obligated to be added to the url argument. contentType - one of [stream, arraybuffer ]

Example:

const { AttachmentProcessor } = require('@elastic.io/component-commons-library');

const getAttachAsStream = async () => (
  await axios.get('http://sample.pdf', { responseType: 'stream' })
).data;
const result = await new AttachmentProcessor().uploadAttachment(getAttachAsStream, 'application/pdf');

const { objectId } = result.data;
const { AttachmentProcessor } = require('@elastic.io/component-commons-library');

const result = await new AttachmentProcessor().getAttachment('http://example.com', 'stream'); // steward storage
const result = await new AttachmentProcessor().getAttachment('http://example.com?storage_type=steward', 'arraybuffer'); // steward storage
const result = await new AttachmentProcessor().getAttachment('http://example.com?storage_type=maester', 'stream'); // maester storage

External API

Environment variables

  • API_RETRIES_COUNT (defaults to 3): maximum amount of retries for 5xx errors. If server still responding 5xx, error will be thrown.
  • API_REQUEST_TIMEOUT (defaults to 15000, min: 500, max: 120000): specifies the number of milliseconds before the request times out. If the request takes longer than timeout, the request will be aborted.
  • axiosReqWithRetryOnServerError (use with .call() to pass context, implement it as a method of class with logger and cfg (value of configuration object for current action) values in a constructor) - function which makes axios request by specified request-config, making logging and error handling:
    1. If 5xx error occurred, it will be retried maximum API_RETRIES_COUNT times, each retry will be delayed with exponentialSleep function.
    2. If 4xx error occurred - error will be thrown.
    3. If action cfg has doNotThrow404 set to true: 404 error won't be treated as error.
      Look on examples below.
  • getErrMsg - forms error message from axios-response.
  • getRetryOptions - return valid values for envs API_RETRIES_COUNT and API_REQUEST_TIMEOUT. If values are higher or lower the limit - they'll be overwritten by default values.
  • sleep - return promise which resolves after N time.
  • exponentialDelay - returns number of milliseconds depending to current retry. See exponential backoff to explanation.
  • exponentialSleep - return promise which resolves after N time. Where N is number of milliseconds from exponentialDelay execution.

Example for axiosReqWithRetryOnServerError function:

class Client {
  private logger: any;

  private cfg: any;

  constructor(emitter, cfg) {
    this.logger = emitter.logger;
    this.cfg = cfg;
  }

   public async apiRequest(options: AxiosRequestConfig): Promise<any> {
    try {
      const response = await axiosReq.axiosReqWithRetryOnServerError(this, requestOptions);
      return response.data;
    } catch (error) {
      if (error.response?.status === 401) {
       // update token
      }
      throw error;
    }
  }

  public async getUserById(id) {
    return this.apiRequest({
      url: `/users/${id}`,
      method: 'GET',
    });
  }
}

Logger

The built in logger uses Bunyan Logger as its base implementation. The available logger methods can be found here.

Example:

const { Logger } = require('@elastic.io/component-commons-library');

const logger = Logger.getLogger();
logger.info('Hello, world');

The getLogger() method takes an optional parameter loggerName that lets you declare multiple different loggers.

License

Apache-2.0 © elastic.io GmbH

版本与发布记录

@elastic.io/component-commons-library 共发布 155 个版本,首次发布于 2019/07/15;过去 12 个月发布了 4 个版本。

版本发布日期距今
4.0.3latest2026/08/142 个月前
4.0.22026/08/132 个月前
4.0.12026/08/133 个月前
4.0.1-dev.1dev2026/08/053 个月前
4.0.02025/08/081.3 年前
4.0.0-dev.22025/08/061.3 年前

其他发布通道:alfa → 0.0.8-alfa.6,dev → 4.0.1-dev.1。

关于 @elastic.io/component-commons-library 的常见问题

@elastic.io/component-commons-library 是什么?

Library for most common component development cases

如何安装 @elastic.io/component-commons-library?

在项目目录运行 npm install @elastic.io/component-commons-library,或使用 pnpm add / yarn add / bun add。

@elastic.io/component-commons-library 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@elastic.io/component-commons-library 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@elastic.io/component-commons-library 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@elastic.io/component-commons-library 可以商用吗?

@elastic.io/component-commons-library 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@elastic.io/component-commons-library 的下载量有多少?

根据 npm 官方下载统计,@elastic.io/component-commons-library 在 2026/10/13 – 2026/11/11 这 30 天内被下载 9,700 次,日均约 323 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@elastic.io/component-commons-library 还在维护吗?

最新版本 4.0.3 发布于 2026/08/14(2 个月前);至今共发布 155 个版本,其中过去 12 个月发布了 4 个;首次发布于 2019/07/15。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。