# @healthie/sdk 中文文档

规范地址：https://npmcn.com/package/%40healthie/sdk/

版本：1\.5\.5
npm 元数据更新时间：2026-08-17T12:59:35.854Z
中文译文更新时间：2026-11-17T18:31:24.114Z
软件包许可：See LICENSE file

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

原始 npm 页面：https://www.npmjs.com/package/%40healthie/sdk
原文对照：https://npmcn.com/package/%40healthie/sdk/?lang=original

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

- 包体积（解压后）：997 kB，8 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：45 个
- peer 依赖：react ^18\.2\.0
- 首次发布：2023-04-04T23:34:13.647Z
- 最新版本发布：2026-08-17T12:59:35.637Z
- 近 30 天下载量：10892（2026-10-18 至 2026-11-16，npm 官方下载统计）
- 已发布版本数：55（近 12 个月 7 个）

## 中文简介

健康反应SDK

## 安装

```sh
npm install @healthie/sdk
```

也可以使用：`pnpm add @healthie/sdk`、`yarn add @healthie/sdk`、`bun add @healthie/sdk`

## README

# 健康 API 的官方反应 SDK

-   [概览](https://npmcn.com/package/%40healthie/sdk/#readme-overview)
-   [在你开始之前](https://npmcn.com/package/%40healthie/sdk/#readme-before-you-start)
-   [安装](https://npmcn.com/package/%40healthie/sdk/#readme-installation)
-   [基本设置](https://npmcn.com/package/%40healthie/sdk/#readme-basic-setup)
    -   [服务器系统渲染](https://npmcn.com/package/%40healthie/sdk/#readme-server-side-rendering)
-   [示例用途](https://npmcn.com/package/%40healthie/sdk/#readme-example-usage)
-   [构成部分](https://npmcn.com/package/%40healthie/sdk/#readme-components)
    -   [对话列表](https://npmcn.com/package/%40healthie/sdk/#readme-conversation-list)
        -   [道具](https://npmcn.com/package/%40healthie/sdk/#readme-props)
        -   [详细使用情况](https://npmcn.com/package/%40healthie/sdk/#readme-detailed-usage)
    -   [聊天](https://npmcn.com/package/%40healthie/sdk/#readme-chat)
        -   [道具](https://npmcn.com/package/%40healthie/sdk/#readme-props-1)
    -   [表单](https://npmcn.com/package/%40healthie/sdk/#readme-form)
        -   [道具](https://npmcn.com/package/%40healthie/sdk/#readme-props-2)
        -   [详细使用情况](https://npmcn.com/package/%40healthie/sdk/#readme-detailed-usage-1)
        -   [样式](https://npmcn.com/package/%40healthie/sdk/#readme-styling)
        -   [文档和文件夹字段](https://npmcn.com/package/%40healthie/sdk/#readme-document-and-folder-fields)
    -   [预订和购买](https://npmcn.com/package/%40healthie/sdk/#readme-booking--buying)
        -   [道具](https://npmcn.com/package/%40healthie/sdk/#readme-props-3)
-   [许可证](https://npmcn.com/package/%40healthie/sdk/#readme-license)

## 概览

Healty SDK是一个用TypeScript所建的React组件库,提供组件和钩子,以方便与Hality的API合作. 目前得到支持的功能包括:

-   聊天
-   表单
-   预订和购买

## 在你开始之前

这个SDK意在用于一个使用Healthie的API的现有项目. 用户认证流量目前不是此 SDK 的一部分, 应该在您的工程中单独执行 .

## 安装

```sh
yarn add @healthie/sdk
yarn add @rails/actioncable graphql-ruby-client
# or
npm i @healthie/sdk
npm i @rails/actioncable graphql-ruby-client
```

## 基本设置

这个SDK在阿波罗客户端上方工作,假设你已经安装并设置了阿波罗客户端.

聊天和其他websocket能力使用ActionCable实现.

以下是阿波罗客户端的基本配置,以使SDK正常工作: 1

```jsx
import {
  ApolloProvider,
  HttpLink,
  ApolloClient,
  InMemoryCache,
  split,
} from '@apollo/client'
import { getMainDefinition } from '@apollo/client/utilities'
import * as ActionCable from '@rails/actioncable'
import ActionCableLink from 'graphql-ruby-client/subscriptions/ActionCableLink'

import { HealthieProvider } from '@healthie/sdk'

const httpLink = new HttpLink({
  uri: 'https://api.gethealthie.com/graphql',
  headers: {
    authorization: 'Basic <user_auth_token>',
    authorizationsource: 'API',
  },
})

const cable = ActionCable.createConsumer(
  'wss://ws.gethealthie.com/subscriptions?token=<user_auth_token>'
)
const wsLink = new ActionCableLink({ cable })

const link = split(
  // split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query)
    if (!('operation' in definition)) {
      return false
    }

    const { kind, operation } = definition
    return kind === 'OperationDefinition' && operation === 'subscription'
  },
  wsLink,
  httpLink
)

const client = new ApolloClient({
  link,
  cache: new InMemoryCache({
    typePolicies: {
      Query: {
        fields: {
          // custom configuration if needed
        },
      },
    },
  }),
})

export function App() {
  return (
    <ApolloProvider client={client}>
      <HealthieProvider userId={'<user_id>'}>
        {/* ... your app ... */}
      </HealthieProvider>
    </ApolloProvider>
  )
}
```

替换 `<user_auth_token>` 在认证过程中获得的用户 API 密钥 `<user_id>` 带有当前认证用户的ID.

更多信息,请访问健康API认证 [这里](https://docs.gethealthie.com/docs/#authentication)。 。 。 .

### 服务器系统渲染

Next.js,Remix,Astro等框架严重依赖服务器端渲染(SSR). 这意味着他们试图在服务器上渲染没有浏览器API的代码. 一些Healthie SDK组件(类似Chat)通过ActionCable库使用WebSockets. 如果您尝试在 Next.js 或其他 SSR 框架中使用以上 ActionCable 代码, 您可能会遇到错误 .

为解决这一问题,遵循以下步骤。 这一解决办法应有利于大多数框架。 如果你更喜欢特定框架的解决办法,例如: [`next/dynamic`](https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading)请查看您框架的文件.

首先,创建一个 `useHydrated.ts` 反应钩 可以帮助我们确定JS是否已经水分了.

```tsx
import { useEffect, useState } from 'react'

let isHydrating = true

export function useHydrated() {
  let [isHydrated, setIsHydrated] = useState(() => !isHydrating)

  useEffect(function hydrate() {
    isHydrating = false
    setIsHydrated(true)
  }, [])

  return isHydrated
}
```

接下来,定义我们 `ClientOnly.tsx` 使儿童只成为客户的部分.

```tsx
import { ReactNode } from 'react'
import { useHydrated } from './useHydrated'

type Props = {
  children(): ReactNode
  fallback?: ReactNode
}

export function ClientOnly({ children, fallback = null }: Props) {
  return useHydrated() ? <>{children()}</> : <>{fallback}</>
}
```

然后确保懒惰地装入阿波罗普罗维德及其客户端定义,从而避免在服务器上运行WebSocket代码.

创建名为的文件 `ApolloForHealthie.tsx` 它包裹了阿波罗普罗维德.

```tsx
type ProviderProps = {
  children: React.ReactNode
}

// rest of the client initialization code (see the "Basic setup" guide)
// ...
// ...
// ...

const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
})

export default function ApolloForHealthie({ children }: ProviderProps) {
  return <ApolloProvider client={client}>{children}</ApolloProvider>
}
```

最后,将新供应商懒散地装入并包装为客户端组件:

```tsx
import { lazy } from 'react'

// it's important to use the React.lazy() instead of regular import
const ApolloForHealthie = lazy(() => import('./ApolloForHealthie'))

function Loading() {
  return (
    <div>
      {/* Ideally this should be the same size as the original component to avoid layout shifts */}
    </div>
  )
}

export default function App() {
  const healthieUserId = '__REPLACE_ME__'

  return (
    <ClientOnlyHydrated fallback={<Loading />}>
      {() => (
        <ApolloForHealthie>
          <HealthieProvider userId={healthieUserId}>
            {/* render Healthie components here */}
          </HealthieProvider>
        </ApolloForHealthie>
      )}
    </ClientOnlyHydrated>
  )
}
```

上述代码将使ApolloClient和Healthie组件成为客户端,同时在服务器上渲染自定义的加载组件. 这阻止了在服务器上使用特定浏览器的API,如ActionCable.

## 示例用途

```jsx
import { ConversationList, Chat, Form } from '@healthie/sdk'
import '@healthie/sdk/dist/styles/index.css'

// This example assumes you defined the Apollo Client according to the
// instructions described in the "Basic setup" section of the Readme

// const client = ...

export default function App() {
  const healthieUserId = '' // obtain during the auth flow

  return (
    <ApolloProvider client={client}>
      {/* HealthieProvider must be rendered before using any of these components */}
      <HealthieProvider userId={healthieUserId}>
        {/* ... */}
        <div className="conversation-list-container">
          <ConversationList />
        </div>
        <div className="chat-container">
          <Chat />
        </div>

        {/* ... */}
        <div>
          <Form id="1">
        </div>

        {/* ... */}
      </HealthieProvider>
    </ApolloProvider>
  )
}
```

## 构成部分

确保导入样式表, 通常在您的应用程序的根组件中 :

```jsx
import '@healthie/sdk/dist/styles/index.css'
```

### 对话列表

此组件将获取当前认证用户的当前对话列表, 并在屏幕上显示 . 若无 `onConversationClick` 或者说 `activeId` 提供了道具,Healthie SDK将管理国家本身.

> : bulb:默认和推荐的方法使这个组件成为"道具"同时留空并让"Healthie Context"管理状态.

```jsx
<ConversationList
  onConversationClick={handleOnConversationClick}
  activeId="<conversation_id>"
/>
```

#### 道具

| 专利名称 | 类型 | 说明 |
| --- | --- | --- |
| `onConversationClick` | `Function` | (可选)在用户点击会话项目时回拨以触发. 如果未提供, 将会将被点击的 conversaton 设定为活动 . |
| `activeId` | `string` 编号 : `null` | 当前选中的对话的 (可选) ID 。 如果不提供,该组件将设定列表中的第一个对话为活动 . |

#### 详细使用情况

```jsx
import { useState } from 'react'

function Example() {
  const [conversationId, setConversationId] = useState(null)

  return (
    <ConversationList
      onConversationClick={(id) => {
        setConversationId(id)
      }}
      activeId={conversationId}
    />
  )
}
```

### 聊天

```jsx
<Chat conversationId="<conversation_id>" />
```

> **3⁄4 ̄ ̧漯B**: 如果你创造了 `ConversationList` 没有自定义道具的组件,不要提供 `conversationId` 为了充分利用Healthie Context的全部能力而设计的道具.

#### 道具

| 专利名称 | 类型 | 说明 |
| --- | --- | --- |
| `conversationId` | `string` | (可选)对话的ID打开. 获取这些信息 [通过图形QL API](https://docs.gethealthie.com/docs/#listing-conversations) 或使用 [对话列表](https://npmcn.com/package/%40healthie/sdk/#readme-conversation-list) 组件。 如果没有提供, 则会从健康协议中进行主动对话 |

这个 `Chat` 组件为主容器的全部高度。 这使得你能够完全控制这个组件的大小和定位.

确保正确指定容器的高度(固定或流体),否则聊天信息可能无法被看到.

> : bulb: 确保向用户提供当前认证的健康用户ID `HealthieProvider`。否则,聊天部分将无法区分收发信件.

### 表单

这个 `Form` 组件在当前用户的上下文中生成一个表格模板(称为自定义模块格式)。 它会自动以用户的数据预填表(如果适用)并代表用户提交表.

```jsx
<Form id="<custom_module_form_id>" />
```

#### 道具

| 专利名称 | 类型 | 说明 |
| --- | --- | --- |
| `id` | `string` | 格式模板(海关模块表)的标识。 您可以通过查询等方式获取表单模板ID [表格完成请求](https://docs.gethealthie.com/docs/#form-completion-requests) 用于当前用户. |
| `submitButtonText` | `string?` | (可选)在提交按钮上显示的文本 。 默认为"屈服". |
| `onSubmit` | `(values: FormFields) => Promise<boolean | void> | boolean | void` | (可选)在提交表单时召回触发 。 回调会收到表格式数据作为参数提交. 你可以选择返回 `false` 从回调来防止表格提交。 在此情况下,您需要使用 [`createFormAnswerGroup`](https://docs.gethealthie.com/docs/#creating-a-filled-out-form-e-g-a-chart-note-or-intake-form) 变相. |
| `onQueryStateChange` | `({ loading, error, data }: QueryState) => void` | (可选的)在加载表单时召回以接收阿波罗查询状态的更改更新. |
| `onMutationStateChange` | `({ loading, error, data }: MutationState) => void` | (可选)在提交表单时召回以接收阿波罗突变状态的更改更新. |

#### 详细使用情况

```jsx
import { useState } from 'react'

function Example() {
  const customModuleFormId = '' // obtain via the GraphQL API

  return (
    <Form
      id={customModuleFormId}
      onSubmit={(data) => {
        // do something with the data
        // return false to prevent the form from submitting
      }}
      onQueryStateChange={({ loading, error, data }) => {
        // access Apollo query status
      }}
      onMutationStateChange={({ loading, error, data }) => {
        // access Apollo mutation statu
      }}
      submitButtonText="Submit form"
    />
  )
}
```

#### 样式

目前 `Form` 组件只通过压倒默认 CSS 类支持自定义样式。 所有字段都有类名 `input-wrapper` 或者说 `form-field-container`。每个字段类型都有自己的类名,因此可以针对特定字段.

此外,Healty SDK的所有组件都被包裹在 `healthie-container` 课. 要覆盖默认样式,您可以通过使用 CSS 特性来杠杆化 CSS 特性并覆盖默认样式 `healthie-container` 类作为父母选择者.

例如:

```css
.healthie-container .input-text {
  /* your styles */
}
```

无需使用此方法 `!important` 以覆盖默认样式,同时仍然能够根据您的需要形成组件样式.

#### 文档和文件夹字段

这个 `Form` 组件支持渲染文档和文件夹字段。 这些字段打开了与健康网络应用中相应的文档或文件夹的链接. 默认情况下,链接会通过通用域来打开应用程序( p[https://security.gethealthie.com (中文(中国大陆) )](https://secure.gethealthie.com/)) (中文(简体) ). 如果你使用标有"健康"的URL,你可以通过 `brandedUrl` 通过下列途径向保健机构提交信息: `HealthieProvider` 组件.

```jsx
<HealthieProvider userId="<user_id>" brandedUrl="https://myapp.example.com">
  <Form id="<form_id>" />
</HealthieProvider>
```

这将通过这样的品牌URL打开文档或文件夹:https://myapp.example.com/documents/{id}/download.

### 预订和购买

这个 `Booking` 组件生成日历和软件包的部件,使客户能够预订预约、浏览服务和购买软件包.

```jsx
<Booking queryString={queryString} />
```

指定日历链接默认与健康生产 URL 生成 。 如果使用有品牌的"健康"后端URL或"健康"中转环境,可以通过 `brandedBackendUrl` 通过下列途径向保健机构提交信息: `HealthieProvider` 组件.

```jsx
<HealthieProvider
  userId="<user_id>"
  brandedBackendUrl="https://staging-api.gethealthie.com"
>
  <Booking queryString={queryString} />
</HealthieProvider>
```

#### 道具

| 专利名称 | 类型 | 说明 |
| --- | --- | --- |
| `queryString` | `string` | 用于使预订部件嵌入的查询字符串 。 这是通过 [共享链接](https://help.gethealthie.com/article/75-integrate-healthie-with-website) 生成于健康板。 例如: `?dietitian_id=1&require_offering=true&offering_id=24&hide_package_images=false`。 。 。 . |

## 许可证

这个SDK根据"健康反应SDK"许可证获得许可. 详见LICENSE文件.

## 常见问题

### @healthie/sdk 是什么？

健康反应SDK

### 如何安装 @healthie/sdk？

在项目目录运行 npm install @healthie/sdk，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react（^18\.2\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @healthie/sdk 支持 TypeScript 吗？

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

### @healthie/sdk 支持 ESM 还是 CommonJS？

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

### @healthie/sdk 可以商用吗？

@healthie/sdk 使用 See LICENSE file 许可。声明的许可为 See LICENSE file，请阅读许可原文确认使用条件。以上为概括，不构成法律意见，请以许可原文为准。

### @healthie/sdk 的下载量有多少？

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

### @healthie/sdk 还在维护吗？

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

