首页 > 解决方案 > 如何在猫鼬的路线中调用路线?

问题描述

从问题中可以看出,我是 Nods js 编写 api 的初学者。我写了一个返回学生所有课程信息的 api

CourseModel.findbyId(){}

现在我想编写另一个返回学生信息 + 他的课程信息的 api。

StudentModel.findbyId(){}

我的问题是我可以在学生 api 中重用我的旧课程 api 吗?还是我必须在学生 api 中再次编写所有课程逻辑

我试图用谷歌搜索,但找不到有用的东西

谢谢

标签: node.jsapi

解决方案


如果你想“复制”逻辑,正确的方法是从路由中调用一个函数。

一个非常伪的例子:

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”。


推荐阅读