node.js - 如何在猫鼬的路线中调用路线?
问题描述
从问题中可以看出,我是 Nods js 编写 api 的初学者。我写了一个返回学生所有课程信息的 api
CourseModel.findbyId(){}
现在我想编写另一个返回学生信息 + 他的课程信息的 api。
StudentModel.findbyId(){}
我的问题是我可以在学生 api 中重用我的旧课程 api 吗?还是我必须在学生 api 中再次编写所有课程逻辑
我试图用谷歌搜索,但找不到有用的东西
谢谢
解决方案
如果你想“复制”逻辑,正确的方法是从路由中调用一个函数。
一个非常伪的例子:
app.get("/course", getCourses);
app.get("/student", getStudent);
function getCoursesWithLogic() {
return CourseModel.findbyId(){}
}
async function getCourses(req, res){
let courses = await getCoursesWithLogic();
}
async function getStudent(req, res){
let student = await StudentModel.findbyId();
let courses = await getCoursesWithLogic();
}
从理论上讲,您也不能定义getCoursesWithLogic
并且只能getCourses
从内部调用,getStudent
但这有点“hacky”。
推荐阅读
- visual-studio - 关闭 Visual Studio 上的调试后如何访问在 docker 上运行的网站
- android - Android Studio - 通过代码获取其他包的路径
- spring - Spring Boot Protobuf 找不到类 com.google.protobuf.UnknownFieldSet$Parser 的序列化程序
- php - Laravel PHP 从特定列获取值
- openlayers - 如何在 openlayer 6 中添加 tms 层?
- python - 当我尝试导入熊猫时,我的 python 控制台总是给我错误
- sql-server - 日期之间的特定时间范围
- android - 取消活动 - handleWindowVisibility:令牌没有活动
- spring-data-jpa - Spring Transactions - 如何访问保存在父事务中的实体
- wso2 - siddhi 有没有办法存储应用程序会话数据?