Reputation: 439
This might be a silly question but I'm quite new to Node/REST and could not find a answer.
Say there is a Request A that asks for Object A ('../student/:studentId'). And there is another Request B that asks for Object B ('.../lecture/:lectureid'). Now Object B will contain some information about the lecture but also the students that attend the lecture.
Now I can think of three possbile ways to assemble Object B:
1.: Call Request A several times from within the processing of Resquest B
2.: Copy and paste the code from the processing of Request A
3.: Create an object that accesses the database and attach it to all request queries:
var dbAccessObject = require('./dbAccess');
app.use(function (req,res,next){
req.dbAccessObject = dbAccessObject;
next();
)};
Which option would you choose? Or is there another, better way?
Upvotes: 1
Views: 151
Reputation: 1064
You don't need to forward requests to yourself. You can handle it within your own code by structuring it nicely. Let's say you have two API routes:
/a: runA();
/b: runB();
And you would like /c to return the result of both /a and /b as if two calls were made. If you have broken your logic down to runA()
and runB()
as above, then /c becomes runC()
:
return {
a: runA(),
b: runB()
}
This is simple when writing synchronous code, but asynchronous code is a bit more difficult because runB()
could return before runA()
; you need to know when they are both finished. I recommend using the async
library for this as a quick win: http://www.informit.com/articles/article.aspx?p=2265406&seqNum=2
Upvotes: 2