# @coveo/platform-client 中文文档

规范地址：https://npmcn.com/package/%40coveo/platform-client/

版本：72\.2\.0
npm 元数据更新时间：2026-10-16T17:53:58.455Z
中文译文更新时间：2026-11-10T20:57:32.579Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40coveo/platform-client
原文对照：https://npmcn.com/package/%40coveo/platform-client/?lang=original
项目主页：https://github.com/coveo/platform-client#readme
源码仓库：https://github.com/coveo/platform-client

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：1.8 MB，1705 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：4 个
- 首次发布：2022-10-05T15:09:32.312Z
- 最新版本发布：2026-10-16T17:53:58.154Z
- 近 30 天下载量：27904（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：289（近 12 个月 41 个）

## 中文简介

这个软件包的主要目标是提供一个方便配置和直截了当的方法,使用JavaScript查询Coveo Cloud API.

## 安装

```sh
npm install @coveo/platform-client
```

也可以使用：`pnpm add @coveo/platform-client`、`yarn add @coveo/platform-client`、`bun add @coveo/platform-client`

## README

# 官方 Coveo Cloud APIs JavaScript 客户端

这个软件包的主要目标是提供一个方便配置和直截了当的方法,使用JavaScript查询Coveo Cloud API.

[![Build Status](https://img.shields.io/travis/coveo/platform-client.svg?style=flat-square)](https://travis-ci.org/coveo/platform-client) [![Npm total downloads badge](https://img.shields.io/npm/dt/@coveo/platform-client?style=flat-square)](https://www.npmjs.com/package/@coveo/platform-client) [![license](https://img.shields.io/hexpm/l/plug.svg?style=flat-square)](https://npmcn.com/package/%40coveo/platform-client/LICENSE) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier) [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=flat-square)](https://github.com/semantic-release/semantic-release)

## 开始

### 构建

```bash
npm i
npm run build
```

### 安装

```bash
npm install @coveo/platform-client
# Typescript types are included in the package
```

### 导入

请注意,这个项目是纯粹的无害环境管理, `require` 无法工作 通用JS的支持有限.

```js
// using default import
import PlatformClient from '@coveo/platform-client';

// using named import
import {PlatformClient} from '@coveo/platform-client';

// using dynamic import, works in CJS ⚠ requires an async context ⚠
const {PlatformClient} = await import('@coveo/platform-client');
```

### 配置

```js
const platform = new PlatformClient({
    /* configuration options */
});
```

### 使用

```js
platform.resource.action({
    /* action dependant options */
});
```

每个动作返回 a [答应](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) 对象.

### 示例

```js
const platform = new PlatformClient({
    organizationId: 'some-coveo-platform-organization-id',
    accessToken: () => 'your-coveo-platform-access-token-or-api-key',
});

// List the organization catalogs
const catalogs = await platform.catalog.list({page: 0, pageSize: 10});
doSometing(catalogs);
```

### 兼容性

这个 `platform-client` 软件包建在顶端 `fetch` API,并不完全得到所有JavaScript运行时环境的支持. 因此,对于节点,我们建议使用节点18或 [未编辑](https://github.com/nodejs/undici) 改为多填充 `fetch` 全球

#### 节点.js 实例

```js
if (!global['fetch']) {
    global['fetch'] = require('undici').fetch;
}
const PlatformClient = require('@coveo/platform-client').default;

const coveoPlatform = new PlatformClient({
    /* options */
});

coveoPlatform.source
    .list()
    .then((res) => {
        console.log(JSON.stringify(res));
    })
    .catch((e) => {
        console.error(e);
    });
```

### 全局配置

也可以为客户端提出的所有请求提供全局请求设置; 简单提供配置 `globalRequestSettings` 选项属性。 这可用于对网络请求应用必要的头或配置. 例如,对于通过代理服务器传送的请求,您可能包含一个代理授权标题 [`Proxy-Authorization` 标题](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Proxy-Authorization)数字 :

#### 节点.js 实例

```js
if (!global['fetch']) {
    global['fetch'] = require('undici').fetch;
}
const PlatformClient = require('@coveo/platform-client').default;

const coveoPlatform = new PlatformClient({
    globalRequestSettings: {
        headers: {
            'Proxy-Authorization': 'Basic YWxhZGRpbjpvcGVuc2VzYW1l',
        },
    },
});

coveoPlatform.source
    .list()
    .then((res) => {
        console.log(JSON.stringify(res));
    })
    .catch((e) => {
        console.error(e);
    });
```

## 文档

这个项目使用TypeScript构建,并自动生成相关的类型声明. 大多数具有 TypeScript 集成的IDE 将显示这些类型声明为自动补全,这样通常不需要引用外部文档 。 因此,已决定不记录任何选项、资源或行动,但主要配置选项除外。 有关本套件所暴露的API的深入文献,请参见: [正式文件门户](https://docs.coveo.com/en/151/cloud-v2-developers/coveo-cloud-v2-for-developers)。 。 。 .

### 配置选项

| 选项 | 需求 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `accessToken` | 对 | 未定义 | 访问符或 API 密钥 . |
| `organizationId` | 对 | 未定义 | 目标组织的独特标识符. |
| `environment` | 选项 | `'production'` | 目标环境. 如下列情况之一: `'development'`, (中文(简体) ), `'stg'` `'production'`, (中文(简体) ), `'hipaa'`; 自动瞄准关联主机. |
| `host` | 选项 | `'https://platform.cloud.coveo.com'` | 目标主机. 用于测试时瞄准本地主机 . |
| `serverlessHost` | 选项 | `'https://api.cloud.coveo.com'` | 无服务器的API的目标主机. |
| `requestHandlers` | 选项 | \[ | 自定义服务器请求处理器 。 见 [请求处理部分](https://npmcn.com/package/%40coveo/platform-client/#readme-request-handling)。 。 。 . |
| `responseHandlers` | 选项 | \[ | 自定义服务器响应处理器 。 见 [错误处理区域](https://npmcn.com/package/%40coveo/platform-client/#readme-error-handling) 详细解释. |
| `region` | 选项 | 地区。 美国 | 目标区域. |

### 处理错误

联合国提出的每一项要求 `platform-client`,一旦解决或拒绝,就由一个(而只有一个)响应处理器处理. 一些非常基本的响应处理器被默认使用,但您可以通过指定自己的行为在 `responseHandlers` [配置选项](https://npmcn.com/package/%40coveo/platform-client/#readme-configuration-option). 其明确顺序确定了其优先权。 表示可以处理响应的数组的第一个处理器被用于处理.

反应处理器被定义为:

```ts
interface ResponseHandler {
    canProcess(response: Response): boolean; // whether the handler should be used to process the response
    process<T>(response: Response): Promise<T>; // defines how the handler processes the response
}
```

示例

```ts
const MySuccessResponseHandler: ResponseHandler = {
    canProcess: (response: Response): boolean => response.ok;
    process: async <T>(response: Response): Promise<T> => {
        const data = await response.json();
        console.log(data);
        return data;
    };
}
```

### 请求处理

有可能界定对请求的自定义请求处理方式 `platform-client` 必要时。 与本报告所述内容类似 [处理错误](https://npmcn.com/package/%40coveo/platform-client/#readme-error-handling)中,您可以在 `requestHandlers`。指定这些请求的顺序界定了处理请求的顺序。 然而,与错误处理不同,所有提供的请求处理器都将被应用于处理请求.

请求处理人被定义为:

```ts
interface RequestHandler {
    canProcess(enrichedRequestInit: EnrichedRequestInit): boolean; // whether the handler should be used to process the request
    process<T>(enrichedRequestInit: EnrichedRequestInit): EnrichedRequestInit; // defines how the handler processes the request
}
```

示例

```ts
const RandomRequestHandler: RequestHandler = {
    canProcess: (enrichedRequestInit: EnrichedRequestInit): boolean => true,
    process: (enrichedRequestInit: EnrichedRequestInit): EnrichedRequestInit => ({
        ...enrichedRequestInit,
        headers: {
            ...enrichedRequestInit.headers,
            'X-Coveo-Platform-Client': 'some-value',
        }
    });
}
```

### 特别请求

有时候,一个特定的 `platform-client` 一次性任务需要配置。 在这种情况下,我们可以利用 `withFeatures()` 方法 `platform-client` 举个例子 这样做将防止产生 `new PlatformClient` 举例来说,只有一个用法.

一个特性被定义为返回一组用于下一个请求的新配置选项的函数.

```ts
type Feature = (currentOptions: PlatformClientOptions) => PlatformClientOptions;
```

何处 `currentOptions` 是客户端实例当前用于提出请求的选项.

示例

```ts
const europeRegion: Feature = (currentOptions) => ({
    ...currentOptions,
    region: Region.EU,
});

const europeOrganizations = await platform.withFeatures(europeRegion).organization.list();
```

多重特性可以同时使用, **每个特性将覆盖上一个返回的选项**。 。 。 .

```ts
const notifyOnSuccess = (message) => (currentOptions) => ({
    ...currentOptions,
    responseHandlers: [
        {
            canProcess: (response) => response.ok,
            process: async (response) => {
                const result = await response.json();
                showSuccessToast(message);
                return result;
            },
        },
        ...currentOptions.responseHandlers,
    ],
});

const notifyOnError = (message) => (currentOptions) => ({
    ...currentOptions,
    responseHandlers: [
        ...currentOptions.responseHandlers,
        {
            canProcess: () => true,
            process: async (response) => {
                const error = await response.json();
                showErrorToast(message);
                throw error;
            },
        },
    ],
});

platform.withFeatures(notifyOnSuccess('It worked!'), notifyOnError('It failed!')).field.delete('unwanted-field-id');
```

### 扩展客户端

如果您想用内部或实验资源来扩展平台客户端的标准能力,可以通过扩展该程序,在自己的项目范围内这样做 `PlatformClient` 课.

```ts
import {API, PlatformClient, PlatformClientOptions, Resource} from '@coveo/platform-client';

class Something extends Resource {
    static baseUrl = `/rest/organizations/${API.orgPlaceholder}/something`;

    list() {
        this.api.get(Something.baseUrl);
    }
}

const experimentalResources: Array<{key: string; resource: typeof Resource}> = [
    {key: 'something', resource: Something},
];

class ExperimentalPlatformClient extends PlatformClient {
    something: Something;

    constructor(options: PlatformClientOptions) {
        super(options);

        experimentalResources.forEach(({key, resource}) => {
            this[key] = new resource(this.API, this.ServerlessAPI);
        });
    }
}

// usage
ExperimentalPlatformClient.something.list();
```

## 捐款

见 [捐款额](https://npmcn.com/package/%40coveo/platform-client/CONTRIBUTING.md)

## 常见问题

### @coveo/platform-client 是什么？

这个软件包的主要目标是提供一个方便配置和直截了当的方法,使用JavaScript查询Coveo Cloud API\.

### 如何安装 @coveo/platform-client？

在项目目录运行 npm install @coveo/platform-client，或使用 pnpm add / yarn add / bun add。

### @coveo/platform-client 支持 TypeScript 吗？

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

### @coveo/platform-client 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @coveo/platform-client 可以商用吗？

@coveo/platform-client 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @coveo/platform-client 的下载量有多少？

根据 npm 官方下载统计，@coveo/platform-client 在 2026/10/11 – 2026/11/09 这 30 天内被下载 27,904 次，日均约 930 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @coveo/platform-client 还在维护吗？

最新版本 72\.2\.0 发布于 2026/10/17（25 天前）；至今共发布 289 个版本，其中过去 12 个月发布了 41 个；首次发布于 2022/10/05。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

