【发布时间】:2021-06-29 13:34:21
【问题描述】:
我有一个带有 Express.js 应用程序的 Node.js。我有这样的文件夹:
src
/models
/router
/store
/api/v1
index.js
我的router 文件夹有一个名为index.router.js 的文件,其中包含我的应用程序的路由,例如:
import UserAPI from '../api/v1/user.api.js'
expressRouter.post('/register', function async function (req, res) {
await UserAPI.registerUser({
EMail: req.body.EMail,
Password: req.body.Password,
Name: req.body.Name
});
上面是一个路由到一个API,所以它进入了我的index.router.js文件。为了在这个端点上执行 API 操作,我为 API 功能创建了另一个名为 user.api.js 的文件,它包含以下内容:
async function registerUser({EMail, Password, Name}) {
// Import method from model file and perform DB action
});
随着应用程序的增长,我开始怀疑我是否让它变得过于复杂,并使用user.api.js 的单独文件创建了一个不必要的层,该文件可能被重构为index.router.js 的一部分。
我不明白的是,为了可扩展性而构建 API 的文件的标准做法是什么?API 端点应该位于 api/v1、api/v2 的单独文件/文件夹中,还是应该是 @987654332 的一部分@?
拥有单独的api 文件的好处之一是可重复使用性。因为它只包含函数而没有路由,所以可以在许多不同的路由器文件中重复使用这些函数。
【问题讨论】:
-
用
One thing that could be advantagous of having separate api files is resuability. Because it only contains functions and no routing, the functions could be reused across many different router files.一针见血,但不仅仅是单独的 HTTP 路由,您还可以重用这些相同的函数来创建其他 API(基于电子邮件、基于 CLI、基于串行等)。跨度>
标签: javascript node.js api express