@coveo/platform-client

中文文档
72.2.0发布于 2026/10/17Apache-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 2.8万

The main goal of this package is to provide an easy to configure and straightforward way of querying Coveo Cloud APIs using JavaScript.

原始使用文档
文档目录16 节
  1. Getting started
  2. Build
  3. Install
  4. Import
  5. Configure
  6. Use
  7. Example
  8. Compatibility
  9. Global Configuration
  10. Documentation
  11. Configuration Options
  12. Error handling
  13. Request handling
  14. Ad hoc requests
  15. Extending the client
  16. Contributing

Official Coveo Cloud APIs JavaScript Client

The main goal of this package is to provide an easy to configure and straightforward way of querying Coveo Cloud APIs using JavaScript.

Build Status Npm total downloads badge license code style: prettier semantic-release

Getting started

Build

npm i
npm run build

Install

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

Import

Note, this project is pure ESM, require won't work and CommonJS support is limited.

// 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');

Configure

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

Use

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

Every action returns a Promise object.

Example

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);

Compatibility

The platform-client package is built on top of the fetch API and is not entirely supported by all JavaScript runtime environments. Consequently, for Node, we recommend using Node 18 or undici to polyfill fetch globally

Node.js example

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);
    });

Global Configuration

It is also possible to provide global request settings for all requests made by the client; Simply provide the configuration in the globalRequestSettings property of the options. This can be useful for applying necessary headers or configurations for network requests. For example, you might include a proxy authorization header for requests routed through a proxy server using the Proxy-Authorization header:

Node.js example

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);
    });

Documentation

This project is built using TypeScript and automatically generates relevant type declarations. Most IDEs with TypeScript integration will display those type declarations as autocompletions, so that you typically will not need to refer to external documentation. Hence, the decision has been made not to document any option, resource, or action, except for the main configuration options. For in-depth documentation on the APIs exposed by this package, please consult our official documentation portal.

Configuration Options

OptionRequiredDefault ValueDescription
accessTokenyesundefinedThe access token or API key.
organizationIdyesundefinedThe unique identifier of the target organization.
environmentoptional'production'The target environment. If one of following: 'development', 'stg' 'production', 'hipaa'; automatically targets the associated host.
hostoptional'https://platform.cloud.coveo.com'The target host. Useful to target local hosts when testing.
serverlessHostoptional'https://api.cloud.coveo.com'The target host for serverless APIs.
requestHandlersoptional[]Custom server request handlers. See Request handling section.
responseHandlersoptional[]Custom server response handlers. See error handling section for detailed explanation.
regionoptionalRegion.USThe target region.

Error handling

Each request made by the platform-client, once resolved or rejected, gets processed by one (and only one) of the response handlers. Some very basic response handlers are used by default, but you can override their behavior by specifying your own in the responseHandlers configuration option. The order in which they are specified defines their priority. Meaning that the first handler of the array that can process the response is used to do so.

A response handler is defined as such:

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
}

Example

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;
    };
}

Request handling

It is possible to define custom request handling for requests made by the platform-client if necessary. Similarly to what is described in Error handling, you can define your own handlers with the help of requestHandlers. The order in which they are specified defines the order in which requests will be handled. However, unlike the error handling, all the provided request handlers will be applied to process requests.

A request handler is defined as such:

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
}

Example

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

Ad hoc requests

Sometimes, a specific platform-client configuration is required for a one-time task. In such use cases, we can leverage the withFeatures() method on the platform-client instance. This will prevent having to create a new PlatformClient instance for just one usage.

A feature is defined as a function that returns a set of new configuration options to be used for the next request.

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

Where currentOptions are the options currently used by the client instance to make requests.

Example

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

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

Multiple features can be used at once, each feature will override the options returned by the previous one.

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');

Extending the client

In cases where you want to expand the standard capabilities of the platform client with internal or experimental resources, you can do so within the scope of your own project by extending the PlatformClient class.

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();

Contributing

See CONTRIBUTING.md

版本与发布记录

@coveo/platform-client 共发布 289 个版本,首次发布于 2022/10/05;过去 12 个月发布了 41 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
72.2.0latest2026/10/1725 天前
72.1.02026/10/1625 天前
72.0.02026/10/1626 天前
71.0.02026/10/1427 天前
70.1.02026/09/111 个月前
70.0.02026/09/102 个月前

其他发布通道:alpha-cli → 0.0.0-clidev.1,alpha → 0.0.0-development.0。

关于 @coveo/platform-client 的常见问题

@coveo/platform-client 是什么?

The main goal of this package is to provide an easy to configure and straightforward way of querying Coveo Cloud APIs using JavaScript.

如何安装 @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 和提交记录判断。