# @fullstory/server-api-client 中文文档

规范地址：https://npmcn.com/package/%40fullstory/server-api-client/

版本：1\.1\.1
npm 元数据更新时间：2024-02-12T20:36:38.706Z
中文译文更新时间：2026-11-15T16:50:30.487Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：219 kB，199 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=14
- 运行依赖：0 个
- 首次发布：2023-05-03T21:39:26.861Z
- 最新版本发布：2024-02-12T20:36:38.476Z
- 近 30 天下载量：15299（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：10（近 12 个月 0 个）

## 中文简介

官方FullStory服务器API客户端SDK为NodeJS.

## 安装

```sh
npm install @fullstory/server-api-client
```

也可以使用：`pnpm add @fullstory/server-api-client`、`yarn add @fullstory/server-api-client`、`bun add @fullstory/server-api-client`

## README

# FullStory 节点JS 客户端 SDK

[![CircleCI](https://dl.circleci.com/status-badge/img/gh/fullstorydev/fullstory-node-sdk/tree/main.svg?style=svg&circle-token=ff82bccfd4023cd504f7b59ec5bd537bc875ec79)](https://dl.circleci.com/status-badge/redirect/gh/fullstorydev/fullstory-node-sdk/tree/main)

官方FullStory服务器API客户端SDK用于NodeJS. SDK是为方便使用而设计的,用于制作服务器对服务器的HTTP API请求. 要了解更多情况 请访问我们 [开发者网站](https://developer.fullstory.com/server/v2/getting-started/)。 。 。 .

为了使用我们的内浏览器模块,我们还提供 [全史浏览器 SDK](https://www.npmjs.com/package/@fullstory/browser)。 。 。 .

## 节点JS支持

-   节点.js 14

## 开始

### 安装

```bash
# npm
npm install @fullstory/server-api-client
# yarn
yarn add @fullstory/server-api-client
```

### 使用量

#### 初始化客户端

使用 `init` 函数以 [您的 API 键](https://developer.fullstory.com/server/v2/authentication/)编辑 `FullStoryOptions` 用于 `init` 函数将用于所有服务器 API 请求.

```ts
import { init } from '@fullstory/server-api-client';

const fsOpts: FullStoryOptions = {
  // apiKey is required to init the FullStory client
  apiKey: '<YOUR_API_KEY>',
  
  // integrationSource is generally intended for FullStory developers
  // or FullStory partners while building integrations.
  //Generally it should be left empty.
  integrationSource: 'INTEGRATION_NAME' 
};

const fsClient = init(fsOpts);
```

#### 用户

-   使用 `users` 访问 [用户 api](https://developer.fullstory.com/server/v2/users/introduction/)
    
    ```ts
    const { users } = fsClient;
    ```
    
-   [创建用户](https://developer.fullstory.com/server/v2/users/create-user/)
    
    ```ts
    const createResponse = await users.create({
      body: {
        uid: 'user123',
        display_name: 'Display Name',
        email: 'user123@example.com',
        properties: {
          pricing_plan: 'paid',
          popup_help: true,
          total_spent: 14.55,
          },
        },
      // optionally provide an idempotencyKey to make
      // the request idempotent
      idempotencyKey: "YOUR_KEY"
      });
    ```
    
-   [获取用户](https://developer.fullstory.com/server/v2/users/get-user/)
    
    ```ts
    // get user by the FullStory assigned id 
    const getResponse = await users.get({
      id: '123456',
      includeSchema: true
    });
    ```
    
-   [获取用户](https://developer.fullstory.com/server/v2/users/list-users/)
    
    ```ts
    // get all users by the application-specified uid
    const listResponse = await users.list({ uid: 'user123' });
    ```
    
-   [更新用户](https://developer.fullstory.com/server/v2/users/update-user/)
    
    ```ts
    // update user by the fullstory assigned id
    const updatedResponse = await users.update({
      id: '123456',
      body: { display_name: 'New Display Name' }
    });
    ```
    
-   [删除用户](https://developer.fullstory.com/server/v2/users/delete-user/)
    
    ```ts
    // delete user by the FullStory assigned id
    await users.delete({ id: '123456' });
    
    // delete user by the application-specified uid
    await users.delete({ uid: 'xyz123' });
    ```
    

#### 活动

-   使用 `events` 访问 [事件 api](https://developer.fullstory.com/server/v2/events/introduction/)
    
    ```ts
    const { events } = fsClient;
    ```
    
-   [创建事件](https://developer.fullstory.com/server/v2/events/create-events/)
    
    ```ts
    const createResponse = await events.create({
      body: {
        session: {
          id: '123:456',
        },
        context: {
          browser: {
            url: 'https://www.example.com',
            initial_referrer: 'https://www.referrer.com',
          },
          location: {
            latitude: 33.748997,
            longitude: -84.387985,
          },
        },
        name: 'Support Ticket',
        timestamp: '2022-03-15T14:23:23Z',
        properties: {
          id: 424242,
          priority: 'Normal',
          source: 'Email',
          title: 'Account locked out',
        }
      }
    });
    ```
    

#### 批量导入任务

-   创建导入任务对象可以让客户端批量导入用户或事件等项目. 首先创建任务对象 :
    
    -   [创建批次用户导入任务](https://developer.fullstory.com/server/v2/users/create-batch-user-import-job/)
    
    ```ts
    // array of users to be imported
    const requests = [
      {
        uid: 'user123',
        display_name: 'Display Name',
        email: 'user123@example.com',
        properties: {
          pricing_plan: 'paid',
          popup_help: true,
          total_spent: 14.5,
        },
      },
      {
        uid: 'user456',
      },
      {
        uid: 'user789',
        display_name: 'A New User',
      },
    ];
    
    // create a job object
    const job = users.batchCreate({
      body: { requests },
      // include schema in the server response
      // when retrieving imported users
      includeSchema: true,
    });
    
    // you can add more requests before executing
    job.add(
      { display_name: 'Someone Else' },
      { display_name: 'Last User' },
    );
    ```
    
-   [创建批次事件导入任务](https://developer.fullstory.com/server/v2/events/create-batch-events-import-job/)
    
    ```ts
    // array of events requests to be imported
    const requests = [
      {
        user: {
          id: '123456',
        },
        session: {
          use_most_recent: true,
        },
        context: {
          web: {
            url: 'https://www.example.com',
          },
        },
        name: 'Support Ticket',
        timestamp: '2022-03-15T14:23:23Z',
        properties: {
          source: 'Email',
          title: 'Account locked out',
        },
      },
    ];
    
    // create a job object
    const job = events.batchCreate({ 
      body: { requests }
      includeSchema: true,
    });
    
    // you can add more requests before executing
    job.add({
        user: {
          id: '999999',
        },
        name: 'Events - 1',
        timestamp: '2022-03-15T14:23:23Z',
      },{
        user: {
          id: '100000',
        },
        name: 'Events - 2',
        timestamp: '2022-03-15T14:23:23Z',
      });
    
    job
      // register listeners before executing
      .on('created', job => {
        console.log('batch job successfully created', job.getId());
      })
      .on('processing', job => {
        console.log('get notified when job status polled and is still processing', job.getId());
      })
      .on('error', error => {
        console.log('an error had occurred during the import', error);
      })
      .on('abort', error => {
        console.error('an unrecoverable error had occurred and the job had been aborted', error);
      })
      .on('done', (imported, failed) => {
        console.log('the batch imported job is done');
        console.log('items successfully imported', imported);
        console.log('items failed to be imported', failed);
      })
    
      // execute the job by calling the server API
    job.execute();
    ```
    

> 注: 任意 `error`, (中文(简体) ), `abort` 或者说 `done` 任务执行后注册的收听者,如果出现任何错误,或者任务已经分别中止或完成,可以立即调用该任务的任何历史数据.

-   批量导入工作生命周期.
    
    可选事件听众可以被添加到批量导入任务. 批量进口工作将管理下列生命周期:
    
    1.  当工作 `execute` 调用方法,向服务器提出 API 请求以创建导入任务 :
    
    -   [用户](https://developer.fullstory.com/server/v2/users/create-batch-user-import-job/)
    -   [事件](https://developer.fullstory.com/server/v2/events/create-batch-events-import-job/)
    
    2.  一旦成功创造了工作, `created` 与任务元数据一起引用听众.
        
    3.  然后该工作开始在服务器 API 上进行民调,以获得一个间隔的最新工作状态:
        
    
    -   [用户](https://developer.fullstory.com/server/v2/users/get-batch-user-import-status/)
        
    -   [事件](https://developer.fullstory.com/server/v2/events/get-batch-events-import-status/)
        
        每一次成功的民意测验都会引用 `processing` 听众.
        
    
    4.  当工作状况达到 `done` 状态( 要么 `COMPLETED` 或者说 `FAILED`),该工作会自动开始取回所导入的物品,通过将"获得批量导入"API:
    
    -   [用户](https://developer.fullstory.com/server/v2/users/get-batch-user-imports/)
        
    -   [事件](https://developer.fullstory.com/server/v2/events/get-batch-events-imports/)
        
        或“获得批次错误” API 如果有错误:
        
    -   [用户](https://developer.fullstory.com/server/v2/users/get-batch-user-import-errors/)
        
    -   [事件](https://developer.fullstory.com/server/v2/events/get-batch-events-import-errors/)
        
        最后还有 `done` 随结果而引用听众.
        
    
    5.  这个 `error` 每当遇到错误时,听众都被称为,可能不止一次.
        
    6.  这个 `abort` 如果发生了无法恢复的错误,例如遇到多次API故障,超过最多复试次数,每工作只叫一次听众.
        
-   重新开始工作
    
    如果一项工作已经成功创建,但因某种原因中止,您可以通过拨打电话重启同一工作的投票 `restart`。 。 。 .
    
    ```ts
    // restart failed job
    const job = events.batchCreate({
      body: { requests }
    });
    job.on('abort', () => {
      // logic to determine if should restart
      job.restart();
    });
    
    // Or
    // restart a failed job with a job id
    const job = events.batchCreate().restart('your-job-id');
    ```
    

#### 批量任务选项

每种工作都可以用不同的 `BatchJobOptions` 需要的时候.

```ts
const options: BatchJobOptions = {
  // poll job status every one minute
  pollInterval: 60000,
  // retry 5 times on API errors before aborting
  maxRetry: 5,
}

const createResponse = await users.batchCreate(
    { 
      body: { requests: [{ uid: 'user123' }] },
      includeSchema: true,
    },
    options
);
```

### 多个批次的导入任务

建议在某一时间进行一批资源类型的进口工作。 但是,如果您需要通过调用创建多个批量导入工作 `batchCreate` 无数次。 工作可以同时执行。 在这种情况下,服务器API可能返回限制出错的速率. 建议调整 `pollInterval` 选项.

如果遇到速率限制或其他瞬间错误, 批量导入任务执行将会重试, 最多可重试数 .

## 处理错误

-   `init` 当所需的字段不能满足时,可能会出错.
    
-   FullStory 客户端中的函数可能抛出 `FSError` 对象。 对于进口工作 `FSError` 对象提供给 a `error` 召回电话.
    
-   如有必要 `name` 字段识别出错的类型。 SDK还提供 `isFSError` 函数以检查一个错误对象是否为已键入 `FSError`。 。 。 .
    

见 [错误](https://github.com/fullstorydev/fullstory-node-sdk/tree/main/src/errors) 更多信息.

```ts
try {
  ...
} catch (err: unknown) {
  if (isFSError(err)) {
    switch (err.name) {
       case FSErrorName.ERROR_INVALID_ARGUMENT:
        console.log('An argument provided to the SDK is invalid.');
        break;
      case FSErrorName.ERROR_RATE_LIMITED:
        console.log('FullStory server API returned HTTP 429 Too Many Requests.');
        console.log(`received 'retry - after' header, retry in ${err.getRetryAfter()} milliseconds.`);
        break;
      case FSErrorName.ERROR_PARSE_RESPONSE:
        console.log('Unable to parse FullStory server API responses.');
        console.log(`Raw response received ${(err as FSParserError).fsErrorPayload}.`);
        break;
      case FSErrorName.ERROR_FULLSTORY:
        // API errors except 429s
        console.log('FullStory server API returned non-2xx responses.');
        console.log(`Status: ${(err as FSApiError).httpStatusCode}.`);
        console.log(`Response: ${(err as FSApiError).fsErrorPayload}.`);
        break;
      case FSErrorName.ERROR_TIMEOUT:
        console.log('Timeout exceeded while making FullStory server API requests.');
        break;
      case FSErrorName.ERROR_MAX_RETRY:
        console.log('Max number of retries exceeded during batch import job execution.');
        break;
      case FSErrorName.ERROR_UNKNOWN:
        console.log('Unexpected error occurred.');
        break;
    }
  }
}
```

## 常见问题

### @fullstory/server-api-client 是什么？

官方FullStory服务器API客户端SDK为NodeJS\.

### 如何安装 @fullstory/server-api-client？

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

### @fullstory/server-api-client 支持 TypeScript 吗？

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

### @fullstory/server-api-client 支持 ESM 还是 CommonJS？

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

### @fullstory/server-api-client 需要什么版本的 Node\.js？

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

### @fullstory/server-api-client 可以商用吗？

@fullstory/server-api-client 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @fullstory/server-api-client 的下载量有多少？

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

### @fullstory/server-api-client 还在维护吗？

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

