【问题标题】:Generate a json schema without starting a server? [closed]在不启动服务器的情况下生成 json 模式? [关闭]
【发布时间】:2018-01-07 14:17:47
【问题描述】:

是否有一个独立的工具可以将模块化的 graphql 模式转换为 json 模式?

我有一个使用 apollo-graphql 和 graphql-tools makeExecutableSchema 的 graphql 服务器。它遵循here 描述的模式

// schema.js
import { makeExecutableSchema } form 'graphql-tools';
const Author = `type Author { ... }`;
const Post   = `type Post   { ... }`;
const Query  = `type Query  { ... }`;

export const typeDefs = [Author, Post, Query];

export const schema = makeExecutableSchema({
  typeDefs: typeDefs,
  resolvers: { ... },
});

如何创建schema.json 表单typeDefs 或schema?


我需要一个 json 模式来使用 relay-compiler 或 apollo-codegen。 apollo-codegen 包含此脚本以从 graphql 服务器创建模式...

apollo-codegen introspect-schema http://localhost:8080/graphql --output schema.json

...但我想在自动构建中创建模式并运行 apollo-codegen。我不想创建服务器。


我会将此作为答案提交,但该问题已被标记为离题¯\_(ツ)_/¯

@daniel-rearden 的回答为我指明了正确的方向。 makeExecutableSchema 返回一个GraphQLSchema,因此可以使用graphql 的printSchema 和introspectionQuery 来获取模式的json 或graphql 语言表示。

// export.js
import { schema } from './schema.js'
import { graphql, introspectionQuery, printSchema } from 'graphql';

// Save json schema
graphql(schema, introspectionQuery).then(result => {
  fs.writeFileSync(
    `${yourSchemaPath}.json`,
    JSON.stringify(result, null, 2)
  );
});

// Save user readable type system shorthand of schema
fs.writeFileSync(
  `${yourSchemaPath}.graphql`,
  printSchema(schema)
);

【问题讨论】:

    标签: graphql apollo apollo-server


    【解决方案1】:

    有graphql-to-json。我相信有一个 CLI 工具可以做到这一点。

    或者,您可以编写自己的脚本并使用node 执行它。您不必启动服务器来运行查询,您只需要一个模式,就可以直接针对它运行查询。您可以查看示例here。

    【讨论】:

    • 好的,看起来makeExecutableSchema 返回了一个 GraphQLSchema。您来自relays docs 示例的示例可能会起作用。
    猜你喜欢
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    相关资源
    最近更新 更多