# @frontside/hydraphql 中文文档

规范地址：https://npmcn.com/package/%40frontside/hydraphql/

版本：0\.1\.3
npm 元数据更新时间：2026-09-30T21:07:08.199Z
中文译文更新时间：2026-11-15T15:12:46.549Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40frontside/hydraphql
原文对照：https://npmcn.com/package/%40frontside/hydraphql/?lang=original
项目主页：https://frontside.com/
源码仓库：https://github.com/thefrontside/HydraphQL

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

- 包体积（解压后）：397 kB，153 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：11 个
- peer 依赖：graphql ^16\.0\.0，dataloader ^2\.0\.0，graphql-modules ^2\.0\.0
- 首次发布：2023-09-13T08:57:14.230Z
- 最新版本发布：2024-02-22T21:06:19.968Z
- 近 30 天下载量：10399（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：6（近 12 个月 0 个）

## 中文简介

使用 DRY 工具,然后将您的 GraphQL 计划水化

## 安装

```sh
npm install @frontside/hydraphql
```

也可以使用：`pnpm add @frontside/hydraphql`、`yarn add @frontside/hydraphql`、`bun add @frontside/hydraphql`

## README

# 水环QL

HydraphQL 提供了通过还原来组织您的 Schema 的功能 重复并用 [图QL 模块](https://the-guild.dev/graphql/modules) 定义新 类型和如何解决它们.

-   [指令 API](https://npmcn.com/package/%40frontside/hydraphql/#readme-directives-api)
    -   [`@field`](https://npmcn.com/package/%40frontside/hydraphql/#readme-field)
    -   [`@implements`](https://npmcn.com/package/%40frontside/hydraphql/#readme-implements)
    -   [`@discriminates`](https://npmcn.com/package/%40frontside/hydraphql/#readme-discriminates)
    -   [`@discriminationAlias`](https://npmcn.com/package/%40frontside/hydraphql/#readme-discriminationalias)
    -   [`@resolve`](https://npmcn.com/package/%40frontside/hydraphql/#readme-resolve)
-   [开始](https://npmcn.com/package/%40frontside/hydraphql/#readme-getting-started)
    -   [图QL 应用程序](https://npmcn.com/package/%40frontside/hydraphql/#readme-graphql-application)
    -   [扩展Schema](https://npmcn.com/package/%40frontside/hydraphql/#readme-extending-your-schema-with-a-custom-module)
    -   [@graphql-codegen/ Type 脚本](https://npmcn.com/package/%40frontside/hydraphql/#readme-graphql-codegentypescript)

## 指令 API

通过图形QL模块,您可以构建您的图形ql代码基础, 但您仍然需要使用 TypeScript 代码来写解析器 。 不过, hydraphQL最重要的优势之一是,大多数的 您不需要写入任何类型脚本 。 相反,你可以告诉 GraphQL 通过直接向Schema添加关于它应该做什么的提示 哪个字段映射到什么。 这些提示叫做 `directives`。 。 。 .

以下指令将告诉 GraphQL 如何写入解析器 自动,所以你不用.

### `@field`

@ field 指令允许您访问对象的属性 使用给定路径。 它允许您指定一个字段的解析器 完全没有写一个真正的解析器 下 盖子,它为你创造了解药。 要看到这个行动, 检查出来 [`catalog.graphql`](https://github.com/thefrontside/playhouse/blob/main/plugins/graphql-backend-module-catalog/src/catalog/catalog.graphql) 使用 `@field` 广泛指令取回模块 属性类 `namespace`, (中文(简体) ), `title` 还有其他.

1.  绘图 `namespace.name` 从源数据到 `Entity#name` 字段 :

```graphql
type Entity {
  name: String! @field(at: "namespace.name")
}
```

2.  如果源路径的字段包含点 `{ spec: { "data.label": "..." } }`,可以使用数组 :

```graphql
type Entity {
  label: String @field(at: ["spec", "data.label"])
}
```

3.  如果找不到字段, 您可以指定默认值为倒计时 :

```graphql
type Entity {
  tag: String! @field(at: "spec.tag", default: "N/A")
}
```

### `@implements`

这个 `@implements` 指令允许您从另一个字段继承 接口。 我们创建这个指令是为了更容易执行 从其他接口继承的接口。 它使图形QL类型 类似于 TypeScript 中的扩展类型。 在类型脚本中,当一个类 继承另一类, 孩子类自动继承 父类的属性和方法。 这个功能没有 在 GraphQL 有等同的图形。 没有这个指令 `Service` graphQL 中的接口需要重新执行许多字段 定义了导致大量重复的已执行接口.

1.  使用此指令定义新类型 包括父界面的所有属性.

```graphql
type Service @implements(interface: "Component") {
  endpoint: String! @field(at: "spec.endpoint")
}
```

在产出计划中,它转变为:

```graphql
type Service implements Component & Entity & Node {
  id: ID!
  name: String!
  kind: String!
  namespace: String!
  # ... rest `Entity` and `Component` fields ...

  endpoint: String!
}
```

### `@discriminates`

这个 `@discriminates` 指令告诉 GraphQL App 接口 被某个特定值歧视到另一个接口或类型. 按路径排列的值 `with` 参数用于确定 键入接口应解决.

```graphql
interface Entity
  @implements(interface: "Node")
  @discriminates(with: "kind") {
    # ...
  }

type Component @implements(interface: "Entity") {
  # ...
}
type Service @implements(interface: "Entity") {
  # ...
}
```

_注:本例中,如果我们掌握下列数据: `Entity` 类型,它已经 `kind` 字段_ _与 `Component` 值,这意味着数据将被解决到 `Component` 类型_

当运行时间数据没有值时有一个特殊的情况 用于区分界面或没有类型 和数值相符 在这种情况下,你可以定义 `opaqueType` 参数

```graphql
interface Entity
  @implements(interface: "Node")
  @discriminates(with: "kind", opaqueType: "OpaqueEntity") {
    # ...
  }
```

在这种情况下,如果 `kind` 字段与任何计划类型不符, 页:1 `OpaqueEntity` 类型将被使用。 您不需要定义此类型, GraphQL 插件会为你生成它 .

还有另一种方法通过使用 `generateOpaqueTypes` 选项.

### `@discriminationAlias`

默认值从 `with` 参数用于找到类型为-is或转换为PascalCase. 有时需要将数值与有不同名称的类型相匹配. 在这种情况下,你可以使用 `@discriminationAlias` 指令.

```graphql
interface API
  @implements(interface: "Node")
  @discriminates(with: "spec.type")
  @discriminationAlias(value: "openapi", type: "OpenAPI") {
    # ...
  }

type OpenAPI @implements(interface: "API") {
  # ...
}
```

这意味着,当 `spec.type` 等于 `openapi`,则 `API` 界面将被解析为 `OpenAPI` 类型.

### `@resolve`

这个 `@resolve` 指令类似于 `@field` 指令,但改为 从源数据中解出一个字段,它从第三方中解出一个字段 API (英语). 如果您想要在您的计划中添加字段, 则此选项很有用 来源数据中已有,但可从另一个API中获取.

1.  要做到这一点,首先需要创建数据记录器 `createLoader` 函数

```ts
import querystring from "querystring";
import { createLoader, NodeQuery } from "@frontside/hydraphql";

export const loader = createLoader({
  async ExampleCom(queries: NodeQuery[]) {
    return Promise.all(
      queries.map(async ({ ref, args }) => {
        const response = await fetch(
          `https://example.com/api/${ref}?${querystring.stringify(args)}`,
        );
        return response.json();
      }),
    );
  },
});
```

2.  那你可以用这个 `@resolve` 指定您 API 的加载器名称的指示 :

```graphql
type Project {
  tasks: [Task!] @resolve(at: "spec.projectId", from: "ExampleCom")
}
```

## 开始

### 图QL 应用程序

由于 HydraphQL 使用 GraphQL 模块 `createGraphQLApp` 返回图形QL应用程序 它可用于所有流行的 GraphQL 服务器,如 `apollo-server`, (中文(简体) ), `express-graphql`, (中文(简体) ), `graphql-yoga` 还有其他.

1.  通过使用创建应用程序 `createGraphQLApp` 函数

```ts
import {
  createGraphQLApp,
  createLoader,
  NodeQuery,
} from "@frontside/hydraphql";
import modules from "./modules";

export async function main() {
  const application = await createGraphQLApp({ modules });
  const loader = createLoader({
    async MyAPI(queries: NodeQuery[]) {
      // ...
    },
  });

  //...
}
```

2.  [使用您的 GraphQL 服务器的应用程序](https://the-guild.dev/graphql/modules/docs/get-started#use-your-application)

_页:1_ 您可以找到如何使用 HydraphQL 的简单示例 `graphql-yoga` 内 [`examples/graphql-yoga`](https://npmcn.com/package/%40frontside/hydraphql/examples/graphql-yoga) 目录.

### 用自定义模块扩展您的计划

要扩展您的方案, 您将使用 GraphQL Schema 定义定义 语言,然后(可选择的)写解析器来处理各种类型 你所定义的.

1.  创建模块目录,用于存储您的 GraphQL 模块, 例如 `./src/modules`
2.  创建模块目录 `my-module` 那边
3.  创建 GraphQL 计划文件 `my-module.graphql` 模块目录中

```graphql
extend type Query {
  hello: String!
}
```

此代码添加 a `hello` 区域 `Query` 类型。 接下来,我们将 编写包含此方案及其解析器的模块.

4.  创建 GraphQL 模块文件 `my-module.ts` 模块目录中

```ts
import { loadFilesSync } from "@graphql-tools/load-files";
import { createModule } from "graphql-modules";

export const myModule = createModule({
  id: "my-module",
  dirname: __dirname,
  typeDefs: loadFilesSync(require.resolve("./my-module.graphql")),
  resolvers: {
    Query: {
      hello: () => "world",
    },
  },
});
```

## `@graphql-codegen`脚本

如果您使用 `@graphql-codegen` 生成输出计划以用于 校验前端查询和/或类型脚本以进行类型检查 GraphQL 模块解析器, 您需要修改 `@graphql-codegen` 相会.

1.  首先创建一个 `schema.ts` 文件为 `transformSchema` 函数并传递您的 GraphQL 文件

```ts
// ./src/schema.ts
import { transformSchema } from "@frontside/hydraphql";
import { printSchemaWithDirectives } from "@graphql-tools/utils";
import { MyModule } from "./modules/my-module/my-module";

export const schema = printSchemaWithDirectives(transformSchema([MyModule]));
```

2.  那你需要更新 `schema` 选项 `codegen.ts`

```ts
import { CodegenConfig } from "@graphql-codegen/cli";
import { schema } from "./src/schema";

const config: CodegenConfig = {
  schema,
  generates: {
    /* ... */
  },
};

export default config;
```

## 常见问题

### @frontside/hydraphql 是什么？

使用 DRY 工具,然后将您的 GraphQL 计划水化

### 如何安装 @frontside/hydraphql？

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

### @frontside/hydraphql 支持 TypeScript 吗？

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

### @frontside/hydraphql 支持 ESM 还是 CommonJS？

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

### @frontside/hydraphql 可以商用吗？

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

### @frontside/hydraphql 的下载量有多少？

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

### @frontside/hydraphql 还在维护吗？

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

