node.js项目结构中数据访问层和服务有什么区别

问题描述

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

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

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

解决方法

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),这是一组构成良好且可扩展的项目的架构规则。