不能在字符串类型定义中使用构造函数类型定义

时间:2019-10-21 09:21:07

标签: graphql graphql-js apollo-server

我正在尝试合并构造函数类型定义和字符串类型定义。这是我的尝试:

我将gql模块的字符串类型定义与user一起使用

modules/user/typeDefs.ts

import { gql } from 'apollo-server';

export const typeDefs = gql`
  type User {
    id: ID!
    name: String
    email: String

    # Use constructor type 'postType'
    posts: [Post]!
  }

  type Query {
    user(id: ID!): User
  }
`;

modules/user/schema.ts

import { resolvers } from './resolvers';
import { typeDefs } from './typeDefs';
import { makeExecutableSchema } from 'apollo-server';

export const userSchema = makeExecutableSchema({ typeDefs, resolvers });

我为post模块使用了构造函数类型定义

modules/post/schema.ts

import { GraphQLObjectType, GraphQLID, GraphQLNonNull, GraphQLString, GraphQLSchema } from 'graphql';
import { IAppContext } from '../../context';

const postType = new GraphQLObjectType({
  name: 'Post',
  fields: {
    id: { type: new GraphQLNonNull(GraphQLID) },
    title: { type: new GraphQLNonNull(GraphQLString) },
    authorId: { type: new GraphQLNonNull(GraphQLID) },
  },
});

const queryType = new GraphQLObjectType({
  name: 'Query',
  fields: {
    post: {
      type: postType,
      args: {
        id: { type: new GraphQLNonNull(GraphQLID) },
      },
      resolve: (_, { id }, { db }: IAppContext) => {
        return db.posts.find((post) => post.id.toString() === id);
      },
    },
  },
});

export const postSchema = new GraphQLSchema({ query: queryType });

现在,我使用userSchema函数将postSchemamergeSchemas合并在一起:

import { mergeSchemas } from 'apollo-server';

import { postSchema } from './modules/post/schema';
import { userSchema } from './modules/user/schema';

export const schema = mergeSchemas({ schemas: [postSchema, userSchema] });

当我尝试启动Apollo GraphQL Web服务器时,得到了以下日志:

☁  apollo-graphql-tutorial [master] ⚡  npx ts-node /Users/ldu020/workspace/github.com/mrdulin/apollo-graphql-tutorial/src/merge-constuctor-types-and-string-types/server.ts
Unknown type "Post".

这甚至不是错误。如果我从posts中删除了type User字段,那么它可以正常工作。

我该如何解决?可以在字符串类型定义中使用构造函数类型定义吗?

依赖版本:

"graphql": "^14.5.4",
"apollo-server": "^2.9.3",

用于重现此问题的最小存储库:https://github.com/mrdulin/apollo-graphql-tutorial/tree/master/src/merge-constuctor-types-and-string-types

0 个答案:

没有答案