如何将GraphQL模式转换为JSON以及最佳的GraphQL模式?

10

我已经搞清楚了,这会给我GraphQLSchema,我希望我可以将其转换为JSON。如何操作呢?

// @flow

import path from 'path';
import fs from 'fs';
import {
  buildSchema,
} from 'graphql';

const main = () => {
  const schemaPath = path.resolve(__dirname, '../schema.graphql');

  console.log(buildSchema(fs.readFileSync(schemaPath, 'UTF8')));
};

main();

如何实现反向转换 - 如何将GraphQL模式的JSON表示转换为GraphQL标记?

我找到的一种方法是:

import {
  printSchema,
  buildSchema,
  buildClientSchema,
  printIntrospectionSchema,
  introspectionFromSchema,
} from 'graphql';

printSchema(buildClientSchema(introspectionFromSchema(buildSchema(fs.readFileSync('./schema.graphql', 'UTF8')))))


然而,这样会丢失很多数据,例如:
type Venue implements Node @preLoad {
  # test
  id: ID!
  fuid: String!
  url: String!
  name: String!
  cinema: Cinema!
  futureEventCount: Int!
  globalCinemaVenue: GlobalCinemaVenue
}

成为:

type Venue implements Node {
  id: ID!
  fuid: String!
  url: String!
  name: String!
  cinema: Cinema!
  futureEventCount: Int!
  globalCinemaVenue: GlobalCinemaVenue
}


你可以使用GotQL在JSON中运行查询,它会负责将数据结构转换为字符串,发送到服务器并获取答案。这是你要找的吗? - Tiago Martins Peres
不,我有一个明确的要求,需要将GraphQL模式语言文档转换为JSON格式,然后再转回去。 - Gajus
这是我的使用案例 https://github.com/gajus/sort-graphql-sdl。我没有想出如何转换为JSON并返回,但事实证明,对于我的使用案例来说,我并不需要那个。 - Gajus
我认为没有办法将GraphQL模式序列化为JSON,然后再反序列化回来而不会丢失信息。类型的序列化已经足够简单了,但无法捕获解析器逻辑、指令等内容。 - Daniel Rearden
2个回答

7

在这里,您不需要外部库,您可以使用 graphql-js 得到所需的所有内容:

import { introspectionFromSchema } from "graphql"
import { GraphQLFileLoader } from "@graphql-tools/graphql-file-loader"
import { loadSchema } from "@graphql-tools/load"

// it can be any source you want here
const schema = loadSchema("./schema.graphql", {
  loaders: [new GraphQLFileLoader()],
})  
const introspection = introspectionFromSchema(schema)

// Tada, you have your introspection

我正在使用与 AWS AppSync 兼容的 GraphQL 模式,并使用 AWS 自定义标量(例如 AWSDate)。如何绕过此验证和错误?未知类型 "AWSDate"。 位于 assertValidSDL (/Users/czl74b/dev-js/graphql-tools/node_modules/graphql/validation/validate.js:135:11) - Jaf

4
您可以使用以下软件包,我相信在发布此帖子时还没有可用:https://www.npmjs.com/package/graphql-2-json-schema
import {
    graphqlSync,
    getIntrospectionQuery,
    IntrospectionQuery
} from 'graphql';

import { fromIntrospectionQuery } from 'graphql-2-json-schema';

const options = {
  ignoreInternals: true,
  nullableArrayItems: true
}

const introspection = graphqlSync(schema, getIntrospectionQuery()).data as IntrospectionQuery;

const jsonSchema = fromIntrospectionQuery(introspection, options);

你是否遇到了Webpack 4的配置示例?当执行代码 const introspection = graphqlSync(schema, getIntrospectionQuery()).data as IntrospectionQuery;时,出现了“unexpected token ... no loaders…” 的错误提示。 - raratiru

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接