将graphql解析器文件拆分为单独的文件

时间:2018-11-25 10:11:49

标签: graphql apollo

我正在使用GraphQL,并且有一个 resolvers.js 文件,如下所示:

const User = require("../models/User");
const Post = require("../models/Post");

module.exports = {
  Query: {
    async users(){...},
    async user(){...},
    async posts(){...},
    async post(){...},
  },
  User: {...},
  Post: {...},
  Mutation: {
    createUser(){...},
    login(){...},
    createPost(){...},
  },
}

但是如果我有更多的模型,查询和变异,文件将非常长。如何将其拆分为单独的文件?一种用于用户查询和变更,一种用于发布等等。还是不可能?也许有一种方法可以将其与 schema.js 文件结合起来?这样我也可以拆分架构,并将User的架构/解析器放入文件中。我仍然是编码的初学者。

3 个答案:

答案 0 :(得分:1)

万一有人在2020年寻找答案,

我有类似的问题, 然后我尝试采用上述方法 但是找到了解决问题的简便方法。

我使用graphql-tools的{​​{1}}解决了问题-https://www.graphql-tools.com/docs/merge-resolvers/

示例代码如下

mergeResolvers

const { mergeResolvers } = require('@graphql-tools/merge'); const clientResolver = require('./clientResolver'); const productResolver = require('./productResolver'); const resolvers = [ clientResolver, productResolver, ]; module.exports mergeResolvers(resolvers); lodash不会区分mergeQuery, 因此在我的情况下会引发错误。

答案 1 :(得分:0)

这就是我的做法。请注意,这是在Typescript中。

您将在单独的文件中定义解析器,例如:

import { DateBidListResolvers } from "../../types/generated";

export const DateBidList: DateBidListResolvers.Type = {
  ...DateBidListResolvers.defaultResolvers,

  list: (_, __) => { // This is an example resolver of Type DateBidList
    throw new Error("Resolver not implemented");
  }
};

然后您将它们汇总到一个文件中,如下所示:

import { Resolvers } from "../../types/generated";

import { Query } from "./Query";
import { User } from "./User";
import { DateBid } from "./DateBid";
import { DateItem } from "./DateItem";
import { Match } from "./Match";
import { Mutation } from "./Mutation";
import { Subscription } from "./Subscription";
import { DateBidList } from "./DateBidList";
import { DateList } from "./DateList";
import { Following } from "./Following";
import { MatchList } from "./MatchList";
import { Message } from "./Message";
import { MessageItem } from "./MessageItem";
import { Queue } from "./Queue";

export const resolvers: Resolvers = {
  DateBid,
  DateBidList,
  DateItem,
  DateList,
  Following,
  Match,
  MatchList,
  Message,
  MessageItem,
  Mutation,
  Query,
  Queue,
  Subscription,
  User
};

然后您可以将解析器导出到您的配置设置中:

import { resolvers } from './resolvers/index';

// ... other imports here

export const server = {
  typeDefs,
  resolvers,
  playground,
  context,
  dataSources,
};

export default new ApolloServer(server);

我希望这会有所帮助!

答案 2 :(得分:0)

实际上,我找到了一种非常简单的方法。在schema.js中,我可以使用lodash合并来合并多个解析器文件,对于typedef,我只使用一个数组。这样,我可以将所有内容拆分为单独的文件。

const { merge } = require("lodash");

module.exports = makeExecutableSchema({
  typeDefs: [typeDefs, userTypeDefs],
  resolvers: merge(resolvers, userResolvers)
});