官方 Coveo Cloud APIs JavaScript 客户端
这个软件包的主要目标是提供一个方便配置和直截了当的方法,使用JavaScript查询Coveo Cloud API.
开始
构建
npm i
npm run build
安装
npm install @coveo/platform-client
# Typescript types are included in the package
导入
请注意,这个项目是纯粹的无害环境管理, require 无法工作 通用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');
配置
const platform = new PlatformClient({
/* configuration options */
});
使用
platform.resource.action({
/* action dependant options */
});
每个动作返回 a 答应 对象.
示例
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或 未编辑 改为多填充 fetch 全球
节点.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 标题数字 :
节点.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的深入文献,请参见: 正式文件门户。 。 。 .
配置选项
| 选项 | 需求 | 默认值 | 说明 |
|---|---|---|---|
accessToken | 对 | 未定义 | 访问符或 API 密钥 . |
organizationId | 对 | 未定义 | 目标组织的独特标识符. |
environment | 选项 | 'production' | 目标环境. 如下列情况之一: 'development', (中文(简体) ), 'stg' 'production', (中文(简体) ), 'hipaa'; 自动瞄准关联主机. |
host | 选项 | 'https://platform.cloud.coveo.com' | 目标主机. 用于测试时瞄准本地主机 . |
serverlessHost | 选项 | 'https://api.cloud.coveo.com' | 无服务器的API的目标主机. |
requestHandlers | 选项 | [ | 自定义服务器请求处理器 。 见 请求处理部分。 。 。 . |
responseHandlers | 选项 | [ | 自定义服务器响应处理器 。 见 错误处理区域 详细解释. |
region | 选项 | 地区。 美国 | 目标区域. |
处理错误
联合国提出的每一项要求 platform-client,一旦解决或拒绝,就由一个(而只有一个)响应处理器处理. 一些非常基本的响应处理器被默认使用,但您可以通过指定自己的行为在 responseHandlers 配置选项. 其明确顺序确定了其优先权。 表示可以处理响应的数组的第一个处理器被用于处理.
反应处理器被定义为:
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
}
示例
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 必要时。 与本报告所述内容类似 处理错误中,您可以在 requestHandlers。指定这些请求的顺序界定了处理请求的顺序。 然而,与错误处理不同,所有提供的请求处理器都将被应用于处理请求.
请求处理人被定义为:
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
}
示例
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 举例来说,只有一个用法.
一个特性被定义为返回一组用于下一个请求的新配置选项的函数.
type Feature = (currentOptions: PlatformClientOptions) => PlatformClientOptions;
何处 currentOptions 是客户端实例当前用于提出请求的选项.
示例
const europeRegion: Feature = (currentOptions) => ({
...currentOptions,
region: Region.EU,
});
const europeOrganizations = await platform.withFeatures(europeRegion).organization.list();
多重特性可以同时使用, 每个特性将覆盖上一个返回的选项。 。 。 .
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 课.
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();
捐款
见 捐款额