You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将GraphQLSchema对象转换为类型定义

Generating Filtered GraphQL Type Definitions from an Introspected GraphQLSchema

Great question! You’re correct that graphql/utilities’s printSchema will spit out the full schema string from a GraphQLSchema object, but if you need to filter specific types or fields, you’ve got two solid approaches to choose from—either tweak the schema object itself before printing, or clean up the printed string afterward. Let’s walk through both:

Approach 1: Manipulate the GraphQLSchema Object Before Printing

This is the more robust method because you’re working directly with the schema’s structured data instead of parsing raw strings. Here’s how to pull it off:

Step 1: Extract the Types You Want

First, grab the specific types you want to keep from your introspected schema. For example, if you only care about the author type:

const { getNamedType, GraphQLSchema, GraphQLObjectType, GraphQLInt } = require('graphql');

// Assume `introspectedSchema` is your existing GraphQLSchema object
const authorType = introspectedSchema.getType('author');

Step 2: Build a Filtered Schema

Next, create a new schema that includes only the types and fields you need. Every valid GraphQL schema requires a root Query type, so we’ll define one that references our filtered type (you can reuse resolve functions from the original schema if needed):

// Create a trimmed-down Query type with just the author field
const filteredQueryType = new GraphQLObjectType({
  name: 'Query',
  fields: {
    author: {
      type: authorType,
      args: { id: { type: GraphQLInt } },
      resolve: introspectedSchema.getQueryType().getFields().author.resolve
    }
  }
});

// Assemble the filtered schema
const filteredSchema = new GraphQLSchema({
  query: filteredQueryType,
  // Add mutations/subscriptions here if you need to filter those too
});

If you want to filter individual fields within a type (e.g., remove the rating field from author), modify the type’s fields before adding it to the new schema:

const filteredAuthorType = new GraphQLObjectType({
  ...authorType.toConfig(),
  fields: Object.fromEntries(
    Object.entries(authorType.getFields()).filter(([fieldName]) => fieldName !== 'rating')
  )
});

Step 3: Print the Filtered Schema

Pass your new schema to printSchema to get the cleaned-up type definitions:

const { printSchema } = require('graphql/utilities');
const filteredSchemaString = printSchema(filteredSchema);
console.log(filteredSchemaString);

Note: If your filtered type references other types (e.g., a book type linked to author), you’ll need to retrieve and include those dependent types in your new schema too.

Approach 2: Post-Process the Printed Schema String

If you prefer a quicker (though less future-proof) solution, print the full schema and then filter the output string. This works for basic cases but relies on the consistent formatting of printSchema:

const { printSchema } = require('graphql/utilities');
const fullSchemaString = printSchema(introspectedSchema);

// Split the schema into individual type blocks (separated by double newlines)
const typeDefinitions = fullSchemaString.split('\n\n');

// Keep only the types you want (e.g., author and Query)
const filteredDefinitions = typeDefinitions.filter(def => 
  def.startsWith('type author') || def.startsWith('type Query')
);

// Join back into a single schema string
const filteredSchemaString = filteredDefinitions.join('\n\n');
console.log(filteredSchemaString);

Just be aware that this might break if the schema includes complex types (like unions or interfaces) or custom formatting comments.

Bonus: Use GraphQL Code Generator (For Introspection JSON)

If you have the raw introspection JSON result (instead of a GraphQLSchema object), graphql-codegen makes filtering straightforward. Configure it to include only specific types in your codegen.yml:

schema: ./introspection.json
generates:
  ./filtered-schema.graphql:
    plugins:
      - schema-ast
    config:
      include:
        - author
        - Query

This will generate a clean schema file with exactly the types you specify.


内容的提问来源于stack exchange,提问作者praveenweb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:41:29