首页 > 解决方案 > 从 graphql-js 切换到本机 graphql 模式?

问题描述

目前正在尝试从graphql-js文字 GraphQL 类型/模式切换,我想知道是否有人对此有任何经验。

让我们来看看这个非常简单的:

const Person = new GraphQLObjectType({
name: 'Person',
  fields: () => ({
    name: {
      type: GraphQLString,
      description: 'Person name',
    },
  }),
});

我想切换到本机 GraphQL 模式语法,即

type Person {
  # Person name 
  name: String
}

但是,这必须是增量的,并且鉴于使用graphql-js,目前最好的解决方案是将 GraphQL 模板文字解析为GraphQLObjectType(或任何其他类型)。有没有人有这样做的经验,不幸的是我似乎找不到任何图书馆。

标签: graphql

解决方案


import { printType } from 'graphql';

printType(Person)

输出:

type Person {
  """Person name"""
  name: String
}

这是演示:

import { expect } from 'chai';
import { printType, printSchema, buildSchema, GraphQLSchema } from 'graphql';

import { logger } from '../util';
import { Person } from './';

describe('test suites', () => {
  it('convert constructor types to string types', () => {
    const stringTypeDefs = printType(Person).replace(/\s/g, '');
    logger.info(printType(Person));

    const expectValue = `
      type Person {
        """Person name"""
        name: String
      }
    `.replace(/\s/g, '');
    expect(stringTypeDefs).to.be.equal(expectValue);
  });

  it('buildSchema', () => {
    const stringTypeDefs = printType(Person);
    const schema = buildSchema(stringTypeDefs);

    expect(schema).to.be.an.instanceof(GraphQLSchema);
  });

  it('printSchema', () => {
    const stringTypeDefs = printType(Person);

    const schema = printSchema(buildSchema(stringTypeDefs));

    logger.info(schema);

    const expectValue = `
      type Person {
        """Person name"""
        name: String
      }
    `.replace(/\s/g, '');

    expect(schema.replace(/\s/g, '')).to.be.eql(expectValue);
  });
});

源代码:

https://github.com/mrdulin/nodejs-graphql/blob/master/src/convert-constructor-types-to-string-types/index.spec.ts


推荐阅读