簡體   English   中英

構建Express + GraphQL項目

[英]Structuring an Express + GraphQL project

如何保持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;

我該如何避免呢?

嗯,這根本沒有達到目的-您的應用程序中的關注點完全分開,而index.js增長的唯一原因是明確要求所有模塊的要求。

我們為類似的問題苦苦掙扎,最終為每個模型目錄( entry/category/service/ )應包含的內容以及導出模塊內部應包含的內容設置了嚴格的接口。 因此,您可以編寫一個整潔的包裝器函數,該函數會在啟動時動態列出所有模型目錄並嘗試加載它們,並期望使用所述接口。 因此,您根本不必在index.js中編寫任何新代碼。 您只需復制粘貼目錄,實現導出的功能,它們就會在應用程序啟動時自動加載。

記住要在加載程序中添加漂亮的錯誤日志記錄,以免在意外破壞接口的約定時避免發生隱式錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM