如何在GraphQL-YOGA中将GraphQL模式分解为多个文件

时间:2020-02-06 16:35:47

标签: javascript graphql

我是GraphQL的新手。我正在尝试将schema.sql文件拆分为多个文件。

第一个问题,这是使用GraphQL做事的标准方法(例如Query.graphql,Mutation.graphql,TypeA.graphql等)

第二,我认为typeDefs(针对graphql-yoga)中的参数允许我传递所有模式文件的位置数组,但对我而言不起作用(请参见下面的代码,了解我得到的错误

这是我的主要index.js文件中的代码:

import { graphQLServer, GraphQLServer } from 'graphql-yoga';
import db from '../database/db';
import Query from './resolvers/Query';
import Mutation from './resolvers/Mutation';
import Post from './resolvers/Post';
import User from './resolvers/User';
import Comment from './resolvers/Comment';
const typeDefs = [
     './schemas/query.graphql', 
     './schemas/mutation.graphql',
     './schemas/user.graphql'
];

const server = new GraphQLServer({
    typeDefs: typeDefs,
    context: { db },
    resolvers: { Query, Mutation, Post, User, Comment }
});

server.start(()=> {
    console.log("Server started on localhost:4000!");
});

这是我遇到的错误:

Error: Field createUser: Couldn't find type User in any of the schemas.
    at collectNode (C:\Websites\Learning-GraphQL - Local Copy\graphql-bootcamp\graphql-basics\node_modules\graphql-import\src\definition.ts:154:15)    
    at C:\Websites\Learning-GraphQL - Local Copy\graphql-bootcamp\graphql-basics\node_modules\graphql-import\src\definition.ts:135:7
    at Array.forEach (<anonymous>)
    at collectNewTypeDefinitions (C:\Websites\Learning-GraphQL - Local Copy\graphql-bootcamp\graphql-basics\node_modules\graphql-import\src\definition.ts:134:26)
    at Object.completeDefinitionPool (C:\Websites\Learning-GraphQL - Local Copy\graphql-bootcamp\graphql-basics\node_modules\graphql-import\src\definition.ts:49:39)
    at Object.importSchema (C:\Websites\Learning-GraphQL - Local Copy\graphql-bootcamp\graphql-basics\node_modules\graphql-import\src\index.ts:127:18) 
    at mergeTypeDefs (C:\Websites\Learning-GraphQL - Local Copy\graphql-bootcamp\graphql-basics\node_modules\graphql-yoga\src\index.ts:456:14)
    at C:\Websites\Learning-GraphQL - Local Copy\graphql-bootcamp\graphql-basics\node_modules\graphql-yoga\src\index.ts:472:32
    at Array.reduce (<anonymous>)
    at mergeTypeDefs (C:\Websites\Learning-GraphQL - Local Copy\graphql-bootcamp\graphql-basics\node_modules\graphql-yoga\src\index.ts:471:21)

如您所见,它说它找不到我的一种类型(用户),但是我确实在User.graphql模式文件中找到它。当我将所有内容都放在一个文件中并且仅将该文件作为typeDefs传递时,它可以正常工作。预先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

const typeDefs = [  
  './schemas/query.graphql',   
  './schemas/mutation.graphql',  
  './schemas/user.graphql'  
];

这只是一个字符串数组

来自文档:

typeDefs-字符串或函数或DocumentNode或上一个数组

您可以进行以下操作:

import Query from './schemas/query.graphql'
import Mutation from './schemas/mutation.graphql'
import User from './schemas/user.graphql'

const typeDefs = [Query, Mutation, User];

需要配置:https://github.com/apollographql/graphql-tag#webpack-preprocessing-with-graphql-tagloader