【问题标题】:what is difference between Data Access layer and service in node.js project structurenode.js项目结构中数据访问层和服务有什么区别
【发布时间】:2021-03-02 11:09:48
【问题描述】:

我刚开始学习 node.js、express 和 mongoose。 在一些教程中,我看到了一些项目结构,比如它们有不同的控制器文件夹,不同的服务,不同的数据访问层。

现在我的问题是服务和数据访问层文件有什么区别,我们在那里保留什么?我们将数据访问层文件保存在我的项目结构中的什么位置?

还有控制器和路由的具体任务是什么?

【问题讨论】:

    标签: node.js project-structure


    【解决方案1】:

    routes 文件是您放置应用程序端点的地方。这些将指您定义的特定应用程序方法。这称为routing

    app.post('/users', userController);
    

    为了清楚起见,在上面的示例中,我们为 /users 路由调用 POST HTTP 方法,并将请求重定向到 userController 方法。

    控制器层更加具体。他负责解析HTTP请求数据并发送到服务层。
    例如:

      async function userController(request, response) {
        const { name, age } = request.body;
    
        const serviceRequestBody = { name, age };
    
        const serviceResponse = await userService(serviceRequestBody);
    
        return response.json(serviceResponse);
    }
    

    服务层 通常是您放置项目规则的位置 (domain specific rules)。 例如:根据用户年龄计算出生年份

    async function createUserService(userData) {
       const birthYear = new Date().getFullYear() - userData.age;
    
       const userFormatedData = {...userData, birthYear }; // the three dots means that we're getting all the information inside userData and placing it inside the new variable.
    
       const dbResult = await userRepository(userFormatedData);
    
       return dbResult;
    }
    

    数据访问层(也可以称为“存储库”)负责getting, posting, updating or deleting来自数据库的信息。

    async function userRepository(userInfo) {
         const dbResult = await db.post(userInfo);
    
         return dbResult;
    }
    

    对于项目结构,更取决于您。我喜欢这样组织我的项目:

    -src
      |-modules
      |     | -user // domain specific entities. If you have other entities, they will be inside another folder with the same structure as this one
      |         |-domain
      |         |-controllers
      |         |-repositories
      |         |-routes
      |         |-services
      |-shared // can be used across any module
            |-utils
            |-providers
    -package.json
    -configFile.json
    

    PS:随着您扩展应用程序,这些抽象可能会随着时间而变化。工程师有责任根据他所面临的情况找出更好的结构。

    如果您想了解有关软件工程的更多信息,请搜索 Domain Driven Design (DDD),它是构成良好且可扩展项目的架构规则集。

    【讨论】:

    • 很好的解释。但是我可以将数据访问层文件放在项目结构中的哪里?
    • 抱歉,我将repositories(数据访问层)添加到文件夹结构和后置脚本中。
    • 只是提示:由于您仍在尝试学习所有这些新技术,请尝试使用一种结构并在您的所有应用程序中遵循该结构,直到您有信心继续前进并创建自己的
    猜你喜欢
    • 2010-09-13
    • 2011-05-08
    • 2017-07-05
    • 2011-02-19
    • 2016-04-30
    • 2020-11-22
    • 2014-02-15
    • 1970-01-01
    • 2014-06-17
    相关资源
    最近更新 更多