构建Express + GraphQL项目

时间:2018-05-02 17:22:20

标签: javascript node.js express structure graphql

如何保持GraphQL API整洁?

我有这个简单的端点有三种可查询的类型,并保持整洁的文件夹结构,如:

/api
  |--/entry
      |--/types.js
      |--/queries.js
      |--/mutations.js
  |--/category
      |--/types.js
      |--/queries.js
      |--/mutations.js
  |--/service
      |--/types.js
      |--/queries.js
      |--/mutations.js
  |--index.js

index.js是我定义根变异和查询的地方,这需要我明确地引用我的类型,查询和突变,所以显然这个文件会随着我添加新类型而增长,这有点挫败了分裂点他们首先在不同的文件夹中。

// src/routes/api/index.js

const LOGGER = require('../../logger')('routes/api');
const EXPRESS_GRAPHQL = require('express-graphql');

// returned when requiring this module
const routes = function (handler) {

    LOGGER.log('info', 'Setting up api routes.');

    const {
        GraphQLSchema,
        GraphQLObjectType,
    } = require('graphql');

    const categoryQuery = require('./category/queries');
    const {
        updateCategory,
        deleteCategory,
        createCategory
    } = require('./category/mutations');

    const serviceQuery = require('./service/queries');
    const {
        updateService,
        deleteService,
        createService
    } = require('./service/mutations');

    const entryQuery = require('./entry/queries');
    const {
        updateEntry,
        deleteEntry,
        createEntry
    } = require('./entry/mutations');

    const RootQuery = new GraphQLObjectType({
        name: 'rootQuery',
        description: 'This is the root query which holds all possible READ entrypoints for the GraphQL API',
        fields: () => ({
            service: serviceQuery,
            category: categoryQuery,
            entry: entryQuery
        })
    });

    const RootMutation = new GraphQLObjectType({
        name: 'rootMutation',
        description: 'This is the root mutation which holds all possible WRITE entrypoints for the GraphQL API',
        fields: () => ({
            updateCategory,
            deleteCategory,
            createCategory,
            updateEntry,
            deleteEntry,
            createEntry,
            updateService,
            deleteService,
            createService
        })
    });

    const Schema = new GraphQLSchema({
        query: RootQuery,
        mutation: RootMutation
    });

    return EXPRESS_GRAPHQL({
        schema: Schema,
        pretty: true,
        graphiql: true,
    });
};

module.exports = routes;

我该如何避免?

1 个答案:

答案 0 :(得分:0)

嗯,它根本没有达到目的 - 你在应用程序中很好地分离了关注点,index.js增长的唯一原因是需要明确要求你所有的模块。

我们在遇到类似的问题时遇到了困难,最终为每个模型目录(entry/category/service/)包含的内容以及导出模块的内容设置了严格的界面。多亏了这一点,您可以编写一个整洁的包装函数,在启动时动态列出所有模型目录并尝试加载它们,期望所述接口。多亏了这一点,您根本不必在index.js中编写任何新代码。您只需复制一个目录,实现导出的函数,它们会在应用程序启动时自动加载。

请记住向您的加载程序添加漂亮的错误记录,以避免在您意外破坏接口合同时出现神秘错误。