繁体   English   中英

如何将 GraphQL 架构转换为 JSON 并最好转换为 GraphQL 架构?

[英]How to convert GraphQL schema to JSON and best to GraphQL schema?

我发现这给了我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
}

您可以使用以下 package 我相信在这篇文章的时间不可用: 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);

您在这里不需要外部库,您拥有所有您需要的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM