# @hasura/metadata 中文文档

规范地址：https://npmcn.com/package/%40hasura/metadata/

版本：1\.0\.2
npm 元数据更新时间：2022-04-05T17:01:38.051Z
中文译文更新时间：2026-11-17T11:43:06.885Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：93.4 kB，6 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- 首次发布：2020-11-05T09:47:38.116Z
- 最新版本发布：2020-11-05T09:57:12.478Z
- 近 30 天下载量：30817（2026-10-18 至 2026-11-16，npm 官方下载统计）
- 已发布版本数：3（近 12 个月 0 个）

## 中文简介

`@hasura/metadata` 包含Hasura元数据V2的TypeScript类型.

## 安装

```sh
npm install @hasura/metadata
```

也可以使用：`pnpm add @hasura/metadata`、`yarn add @hasura/metadata`、`bun add @hasura/metadata`

## README

# @hasura/元数据

`@hasura/metadata` 包含Hasura元数据V2的TypeScript类型.

## 安装

```sh
yarn add @hasura/metadata # npm i @hasura/metadata
```

## 使用量

```ts
import { HasuraMetadataV2, Action, ComputedField } from "@hasura/metadata-types"
```

# 元数据 SDK

## 目录

-   [目录](https://npmcn.com/package/%40hasura/metadata/#readme-table-of-contents)
-   [导言](https://npmcn.com/package/%40hasura/metadata/#readme-introduction)
-   [如何使用( aka TL; DR)](https://npmcn.com/package/%40hasura/metadata/#readme-how-to-use-this-aka-tldr)
-   [演示文稿](https://npmcn.com/package/%40hasura/metadata/#readme-demos)
    -   [类型脚本 SDK](https://npmcn.com/package/%40hasura/metadata/#readme-typescript-sdk)
    -   [元数据 YAML 文件内部的类型检查文件( Docs)](https://npmcn.com/package/%40hasura/metadata/#readme-type-checking--docs-inside-of-metadata-yaml-files)
-   [SDK 用法示例( TypeScript)](https://npmcn.com/package/%40hasura/metadata/#readme-sdk-usage-examples-typescript)
    -   [扩展生成的类功能](https://npmcn.com/package/%40hasura/metadata/#readme-extending-the-generated-class-functionality)
    -   [程序与元数据交互](https://npmcn.com/package/%40hasura/metadata/#readme-programmatically-interacting-with-metadata)
-   [生成器配置文件选项](https://npmcn.com/package/%40hasura/metadata/#readme-generator-config-file-options)
-   [测试配置文件选项](https://npmcn.com/package/%40hasura/metadata/#readme-test-config-file-options)
-   [程序用途](https://npmcn.com/package/%40hasura/metadata/#readme-programmatic-usage)
-   [元数据 IDE 类型检查集成](https://npmcn.com/package/%40hasura/metadata/#readme-metadata-ide-type-checking-integration)
    -   [VS 代码](https://npmcn.com/package/%40hasura/metadata/#readme-vs-code)
    -   [喷气管](https://npmcn.com/package/%40hasura/metadata/#readme-jetbrains)

## 导言

这种repo包含一个从TypeScript或JSON Schema来源生成各种语言的SDK的脚本. 剧本可塑并被从Github Action或git钩等东西中消耗而来.

用于生成哈苏拉元数据V2的 SDK

## 如何使用( aka TL; DR)

_**"我想..." "I want to..."**_

-   向我的 IDE 添加用于元数据文件的类型检查和文档支持
    
    -   见: [元数据 IDE 类型检查集成](https://npmcn.com/package/%40hasura/metadata/#readme-metadata-ide-type-checking-integration)
-   _在我的工程中使用已有的 SDK 输入语言_
    
    -   从中下载 SDK [`/generated`](https://npmcn.com/package/%40hasura/metadata/generated) 目录
    -   跟着指南走 [SDK 用法示例( TypeScript)](https://npmcn.com/package/%40hasura/metadata/#readme-sdk-usage-examples-TypeScript)
-   _生成一个新的 SDK , 用于尚未存在于 `/generated` 目录( 或自定义已有的生成器选项)_
    
    -   更新配置, 在此遵循向导 : [生成器配置文件选项](https://npmcn.com/package/%40hasura/metadata/#readme-generator-config-file-options)
    -   `yarn install` 或者说 `npm install`
    -   `yarn generate-types` 或者说 `npm run generate-types`

## 演示文稿

### 类型脚本 SDK

![](https://npmcn.com/package/%40hasura/metadata/TypeScript-typecheck-demo.gif)

### 元数据 YAML 文件内部的类型检查文件( Docs)

![](https://npmcn.com/package/%40hasura/metadata/json-schema-typecheck-demo.gif)

## SDK 用法示例( TypeScript)

### 扩展生成的类功能

为 TypeScript 生成的 SDK 包含类型, 但也产生一个称为顶级类 `Convert`,其中包含对类型进行运行时间解析和验证的方法。 这些被命名为例如. `Convert.toCronTrigger()` 财务报告和审定财务报表 `Convert.cronTriggerToJson()`数字 :

```ts
public static toCronTrigger(json: string): CronTrigger {
    return cast(JSON.parse(json), r("CronTrigger"));
}

public static cronTriggerToJson(value: CronTrigger): string {
    return JSON.stringify(uncast(value, r("CronTrigger")), null, 2);
}
```

此类可以从另一个文件中被扩展来添加额外的功能. 以下是我们将使用的一个例子,它补充: `diff` 函数和一个 YAML 转换函数.

```ts
// customMetadataConverter.ts
import fs from "fs"
import { load, dump } from "js-yaml"
import { createPatch } from "diff"
import { detailedDiff } from "deep-object-diff"
import {
  Convert as _Convert,
  TableEntry,
  Action,
  CustomTypes,
  CronTrigger,
  HasuraMetadataV2,
} from "../generated/HasuraMetadataV2"

interface DiffOutput {
  structuralDiff: object
  textDiff: string
}

interface WriteDiffOpts {
  folder: string
  file: string
  diffs: DiffOutput
}

export class Convert extends _Convert {
  public static loadYAML = load
  public static dumpYAML = dump
  public static diffYaml = createPatch
  public static diffJson = detailedDiff

  public static clone(obj: any) {
    if (obj == null || typeof obj != "object") return obj
    let temp = new obj.constructor()
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        temp[key] = Convert.clone(obj[key])
      }
    }
    return temp
  }

  public static diff(before: object, after: object): DiffOutput {
    const originalYaml = Convert.metadataToYaml(before)
    const updatedYaml = Convert.metadataToYaml(after)
    const structuralDiff = Convert.diffJson(before, after)
    const textDiff = Convert.diffYaml("", originalYaml, updatedYaml)
    return { structuralDiff, textDiff }
  }

  public static writeDiff(opts: WriteDiffOpts) {
    const { file, folder, diffs } = opts
    fs.writeFileSync(`${folder}/${file}.diff`, diffs.textDiff)
    fs.writeFileSync(
      `${folder}/${file}.json`,
      JSON.stringify(diffs.structuralDiff, null, 2)
    )
  }

  /**
   * Converts metadata objects into YAML strings
   */
  public static metadataToYaml(value: object): string {
    // JSON Stringify + Parse to remove "undefined" key/values from YAML
    return dump(JSON.parse(JSON.stringify(value)))
  }
}
```

### 程序与元数据交互

下面是一个实例,用于显示您在想要脚本您与元数据互动时可能遇到的常见使用大小写 。 它包括:

-   正在装入 `tables.yaml`,以及 `actions.yaml` 文件
-   添加新表格
-   创建 JSON 和文本 diff `tables.yaml`,并写给 `diffs` 文件夹
-   重复上述过程 `metadata.json` (可能为: `metadata.yaml` (a) 国家

```ts
import { Convert } from "./customMetadataConverter"
import {
  TableEntry,
  Action,
  CustomTypes,
  HasuraMetadataV2,
} from "../generated/HasuraMetadataV2"

// Read "tables.yaml" file as text from filesystem
const tablesMetadataFile = fs.readFileSync("./metadata/tables.yaml", "utf8")
// Convert it to JSON object with type annotation using loadYAML utility
const tablesMetadata: TableEntry[] = Convert.loadYAML(tablesMetadataFile)
tablesMetadata.forEach(console.log)

// Read "actions.yaml" file as text from filesystem
const actionMetadataFile = fs.readFileSync("./metadata/actions.yaml", "utf8")
// Convert it to JSON object with type annotation using loadYAML utility
const actionMetadata: {
  actions: Action[]
  custom_types: CustomTypes
} = Convert.loadYAML(actionMetadataFile)
actionMetadata.actions.forEach(console.log)
console.log(actionMetadata.custom_types)

// Make a new table object
const newTable: TableEntry = {
  table: { schema: "public", name: "user" },
  select_permissions: [
    {
      role: "user",
      permission: {
        limit: 100,
        allow_aggregations: false,
        columns: ["id", "name", "etc"],
        computed_fields: ["my_computed_field"],
        filter: {
          id: { _eq: "X-Hasura-User-ID" },
        },
      },
    },
  ],
}

// Clone the tables for comparison after changes using diff()
const originalTablesMetadata = Convert.clone(tablesMetadata)
// Add the new table to tables metadata
tablesMetadata.push(newTable)

// Generate a structural and text diff from the changes between original and now
const tableDiff = Convert.diff(originalTablesMetadata, tablesMetadata)
// Write the diffs to /diffs folder, will output "tables.json" and "tables.diff"
Convert.writeDiff({ folder: "diffs", file: "tables", diffs: tableDiff })
// Ouput the updated "tables.yaml" to filesystem
fs.writeFileSync(
  "./tables-updated.yaml",
  Convert.metadataToYAML(tablesMetadata)
)

// Read "metadata.json"
const metadataFile = fs.readFileSync("./metadata.json", "utf-8")
// Convert.to<typeName> does runtime validation of the type
const allMetadata: HasuraMetadataV2 = Convert.toHasuraMetadataV2(metadataFile)
console.log(allMetadata)

// Clone, add table
const beforeMetadataChanges = Convert.clone(allMetadata)
allMetadata.tables.push(newTable)

// Diff, write diff
const metadataDiff = Convert.diff(beforeMetadataChanges, allMetadata)
Convert.writeDiff({ folder: "diffs", file: "metadata", diffs: metadataDiff })
```

## 生成器配置文件选项

_注释:运行方式 `yarn generate-types`编号 :`npm run generate-types`_

文件 `config.yaml` 可用于向程序传递选项。 这需要:

-   “ TypeScript” 或“ JsonSchema” 的输入语言目标
-   单个文件/ glob 表达式, 或用于生成类型输入文件的文件/ glob 表达式的数组
-   输出目录可以设置,输出文件名将是输入文件的名称(带有新的语言扩展名)
-   存在于 `quicktype_config` 将生成,对象密钥是转到Quicktype的选项 `rendererOptions` 配置

```yaml
# Accepts "TypeScript" or "JsonSchema"
# Override this with --TypeScript or --jsonschema from CLI
selected_input_language: TypeScript

# Glob patterns for the target input files of selected language
# Only the matching SELECTED INPUT LANGUAGE file expression will be used
input_files:
  # Paths can be either a string, or an array of strings
  JsonSchema: "./src/types/**.schema.json"
  TypeScript: ["./src/types/**.ts", "./src/otherfolder/**.ts"]

# Output file directory
output_directory: "./generated"

# Quicktype config per-language
# Config is an object of type "rendererOptions"
# See: https://github.com/quicktype/quicktype/blob/master/src/quicktype-core/language/TypeScriptFlow.ts#L20
quicktype_config:
  # c++: ~
  # crystal: ~
  # csharp: ~
  # dart: ~
  # elm: ~
  # flow: ~
  go:
    package: hasura_metadata
  haskell: ~
  # java:
  #   package: org.hasura.metadata
  # kotlin:
  #   framework: kotlinx
  #   package: org.hasura.metadata
  # objective-c: ~
  # pike: ~
  python:
    python-version: "3.7"
  # ruby: ~
  # rust: ~
  schema: ~
  # swift: ~
  TypeScript: ~
  # rendererOptions:
  #   just-types: true
```

## 测试配置文件选项

_注释:运行方式 `yarn test`编号 :`npm run test`_

测试配置文件用于取出样本输入的JSON文件,并提供给生成的TypeScript SDK进行自动化测试. 想法是有很多样本 `metadata.json` (甚至个体类型,如 `table.yaml` 并对照生成的核查类型对其进行排入.

输入时选择包含元数据类型的TypeScript文件的位置,然后是一组 `jsonInputTests` 与 `files` 作为一个或多个文件路径或 glob 表达式,指向输入 JSON 数据用作类型输入.

例如:

```ts
// myTypes.ts
interface MyType {
  name: string
  age: number
}
```

```js
// test-data1.json
{
  "name": "John",
  "age": 30
}
```

定义是这样的:

```yaml
---
- typeDefinitionFile: "./generated/HasuraMetadataV2.ts"
  jsonInputTests:
    - files: "./src/tests/**.json"
      # This gets called as "Convert.to(expectType)" -> e.g "Convert.toHasuraMetadataV2" in generated TS SDK
      expectType: HasuraMetadataV2
```

![](https://npmcn.com/package/%40hasura/metadata/test-output-sample.png)

## 程序用途

类型生成器理论上既可以作为CLI可执行文件运行,也可以作为库运行. 这样可以自定义行为,IE用于CI/CD管道. 以下是一个例子:

```ts
generateTypes()
  .then((outputs) => {
    console.log("Finished generateTypes(), outputs are", outputs)
    for (let output of outputs) {
      // This is the input file path
      console.log("File:", output.file)
      // This contains the generated text
      console.log("Results:", output.results)
    }
  })
  .catch((err) => {
    console.log("Got error", err)
  })
  .finally(async () => {
    // Convert the generated JSON Schema to YAML, for example
    const generatedFolder = path.join(pathFromRoot, "generated", "/")
    const jsonSchemas = await glob(generatedFolder + "**.json")
    jsonSchemas.forEach(jsonSchemaToYAML)
  })
```

## 元数据 IDE 类型检查集成

曾经尝试(或想要)用手写出Hasura元数据YAML定义,但发现自己经常被拉回用于定义的文档,或者对抗YAML的白空间敏感性? 没有了!

### VS 代码

VS代码在编辑JSON文件时有本地支持提供JSON Schemas. 这个 [由 Redhat 撰写的 YAML 扩展名](https://github.com/redhat-developer/vscode-yaml) 向 YAML 文件提供相同的支持 .

遵循下面的配置, 以便您工程中的 Hasura 元数据 YAML 文件能够进行类型检查、 文档和自动补全 :

_说明: 在未来,这可能会被重新设定为指向在Github上托管了schema链接,这样就不需要手工复制schema文件了._

`.vscode/extensions.json`

```json
{
  "recommendations": ["redhat.vscode-yaml"]
}
```

`.vscode/settings.json`

```json
{
  "json.schemas": [
    {
      "fileMatch": ["**/metadata.json"],
      "url": "./MetadataExport.schema.json"
    }
  ],
  "yaml.schemas": {
    "./ActionsYAML.schema.json": "**/actions.yaml",
    "./AllowListYAML.schema.json": "**/allow_list.yaml",
    "./CronTriggerYAML.schema.json": "**/cron_triggers.yaml",
    "./FunctionsYAML.schema.json": "**/functions.yaml",
    "./QueryCollectionsYAML.schema.json": "**/query_collections.yaml",
    "./RemoteSchemasYAML.schema.json": "**/remote_schemas.yaml",
    "./TablesYAML.schema.json": "**/tables.yaml"
  }
}
```

`./MetadataExport.schema.json`

```json
{
  "type": "object",
  "$ref": "./HasuraMetadataV2.schema.json#definitions/HasuraMetadataV2"
}
```

`./ActionsYAML.schema.json`数字 :

```json
{
  "type": "object",
  "properties": {
    "actions": {
      "type": "array",
      "items": {
        "$ref": "./HasuraMetadataV2.schema.json#definitions/Action"
      }
    },
    "custom_types": {
      "type": "object",
      "$ref": "./HasuraMetadataV2.schema.json#definitions/CustomTypes"
    }
  }
}
```

`./AllowListYAML.schema.json`数字 :

```json
{
  "type": "array",
  "items": {
    "$ref": "./HasuraMetadataV2.schema.json#definitions/AllowList"
  }
}
```

`./CronTriggerYAML.schema.json`数字 :

```json
{
  "type": "array",
  "items": {
    "$ref": "./HasuraMetadataV2.schema.json#definitions/CronTrigger"
  }
}
```

`./FunctionsYAML.schema.json`数字 :

```json
{
  "type": "array",
  "items": {
    "$ref": "./HasuraMetadataV2.schema.json#definitions/Function"
  }
}
```

`./QueryCollectionsYAML.schema.json`数字 :

```json
{
  "type": "array",
  "items": {
    "$ref": "./HasuraMetadataV2.schema.json#definitions/QueryCollectionEntry"
  }
}
```

`./RemoteSchemasYAML.schema.json`数字 :

```json
{
  "type": "array",
  "items": {
    "$ref": "./HasuraMetadataV2.schema.json#definitions/RemoteSchema"
  }
}
```

`./TablesYAML.schema.json`

```json
{
  "type": "array",
  "items": {
    "$ref": "./HasuraMetadataV2.schema.json#definitions/TableEntry"
  }
}
```

### 喷气管

YAML 指令 :

[https://www.jetbrains.com/help/ruby/yaml.html#remote json (英语)](https://www.jetbrains.com/help/ruby/yaml.html#remote_json)

![](https://resources.jetbrains.com/help/img/idea/2020.1/yaml_complete_json.png)

JSON指令:

[https://www.jetbrains.com/help/idea/json.html#ws json schema add custom. \[永久失效連結\] 互联网档案馆的存檔,存档日期2014-12-21](https://www.jetbrains.com/help/idea/json.html#ws_json_schema_add_custom)

![Jetbrains JSON Schema Mapping in Editor](https://www.jetbrains.com/help/img/idea/2020.1/ws_json_schema_no_schema_status_bar.png)

## 常见问题

### @hasura/metadata 是什么？

@hasura/metadata 包含Hasura元数据V2的TypeScript类型\.

### 如何安装 @hasura/metadata？

在项目目录运行 npm install @hasura/metadata，或使用 pnpm add / yarn add / bun add。

### @hasura/metadata 支持 TypeScript 吗？

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

### @hasura/metadata 支持 ESM 还是 CommonJS？

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

### @hasura/metadata 可以商用吗？

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

### @hasura/metadata 的下载量有多少？

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

### @hasura/metadata 还在维护吗？

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

