客户端合并两个GraphQL Schema并自动生成TypeScript类型的方案
下面给你两种处理多GraphQL端点类型生成的方案,包含具体操作步骤和代码示例:
方案一:基于现有Apollo Codegen扩展多端点支持
1. 下载两个端点的自省Schema
修改package.json里的schema脚本,分别下载两个端点的Schema文件:
"schema:download:service1": "npx apollo service:download --endpoint=http://localhost:8080/graphql graphql-schema-service1.json", "schema:download:service2": "npx apollo service:download --endpoint=http://localhost:9090/graphql graphql-schema-service2.json", "schema:download": "npm run schema:download:service1 && npm run schema:download:service2"
2. 合并两个Schema
首先安装合并Schema的工具依赖:
npm install @graphql-tools/merge @graphql-tools/utils graphql -D
然后在项目根目录创建merge-schemas.js脚本:
const { loadSchemaSync } = require('@graphql-tools/load'); const { JsonFileLoader } = require('@graphql-tools/json-file-loader'); const { mergeSchemas } = require('@graphql-tools/merge'); const { printSchema } = require('graphql'); const fs = require('fs'); // 加载两个本地Schema文件 const schema1 = loadSchemaSync('./graphql-schema-service1.json', { loaders: [new JsonFileLoader()] }); const schema2 = loadSchemaSync('./graphql-schema-service2.json', { loaders: [new JsonFileLoader()] }); // 合并Schema const mergedSchema = mergeSchemas({ schemas: [schema1, schema2] }); // 将合并后的Schema输出为SDL文件(也可以输出为JSON) fs.writeFileSync('./graphql-schema-merged.graphql', printSchema(mergedSchema));
在package.json里添加合并脚本:
"schema:merge": "node merge-schemas.js", "schema": "npm run schema:download && npm run schema:merge"
3. 基于合并后的Schema生成类型
修改types脚本,指向合并后的Schema文件:
"types": "npm run schema && apollo client:codegen --localSchemaFile=graphql-schema-merged.graphql --variant=development --target=typescript --addTypename --queries=./src/**/*.graphql --useReadOnlyTypes --globalTypesFile=src/globalTypes.ts . && npm run prettier"
方案二:切换到GraphQL Code Generator(推荐)
GraphQL Code Generator原生支持多端点/多Schema场景,配置更灵活:
1. 安装依赖
npm install @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-apollo-client-helpers -D
2. 创建配置文件
在项目根目录创建codegen.ts:
import type { CodegenConfig } from '@graphql-codegen/cli'; const config: CodegenConfig = { // 配置两个端点的Schema,可以是远程URL也可以是本地文件 schema: [ 'http://localhost:8080/graphql', 'http://localhost:9090/graphql' ], // 指定项目中的查询文件路径 documents: ['./src/**/*.graphql'], // 输出配置 generates: { './src/generated/graphql.ts': { plugins: [ 'typescript', 'typescript-operations', 'typescript-apollo-client-helpers' ], // 对应原Apollo Codegen的参数 config: { addTypename: true, readonlyTypes: true, globalTypesFile: './src/globalTypes.ts' } } }, // 格式化输出代码 hooks: { afterOneFileWrite: ['npm run prettier'] } }; export default config;
3. 添加npm脚本
在package.json里添加:
"codegen": "graphql-codegen --config codegen.ts"
之后直接运行npm run codegen就能生成多Schema对应的类型文件。
内容的提问来源于stack exchange,提问作者justdvl
相关产品推荐
相关产品推荐

