【发布时间】:2021-03-02 11:09:48
【问题描述】:
我刚开始学习 node.js、express 和 mongoose。 在一些教程中,我看到了一些项目结构,比如它们有不同的控制器文件夹,不同的服务,不同的数据访问层。
现在我的问题是服务和数据访问层文件有什么区别,我们在那里保留什么?我们将数据访问层文件保存在我的项目结构中的什么位置?
还有控制器和路由的具体任务是什么?
【问题讨论】:
我刚开始学习 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),它是构成良好且可扩展项目的架构规则集。
【讨论】:
repositories(数据访问层)添加到文件夹结构和后置脚本中。