There is a generic structure of nodejs callback functions :
function(req,res){
//handle callback
}
I just want, callback should work correctly even if sometimes i write in mistake (res, req)
Given mixture of req or res, how do i find which one is actually request and which one is response.
req is an IncomingMessage object and res is a ServerResponse object.
So check for unique properties on each, for example if the particular object has a writeHead() function, then it's the response object.
You may also be able to use instanceof to check: res instanceof http.ServerResponse.
Functions in JavaScript are not programmatically prototyped by parameter names. The length property of a function only provides the number of parameters specified in the definition:
var fn = function (one,two,three) { return "x"; };
console.log(fn.length); // 3
Although there are ways to retrieve these names (see this question), usually procedures simply ignore how you name the parameters of your functions/closures, and instead assume that you are following the proposed API.
For this reason, it remains as the best practice to pay attention to the API and name parameters accordingly. In a Node.js HTTP request listener, the request comes always before the response (it is documented and many examples are available). As mentioned by other answers, you can dynamically check whether the request is an http.IncomingMessage or whether the response is an http.ServerResponse, but it seems to me that you can avoid introducing an overhead just with proper naming.
With that said, given the variables req and res, it is easy to make a check at the top of a function body, like the code below. However, do note that this would only be remedying what can be prevented by just following the API contracts, and as thus I cannot recommend it (unless you really want to make functions with a more flexible API).
function(res,req) {
if (req instanceof http.ServerResponse) {
// wrong order, swap.
var t = req;
req = res;
res = t;
}
// handle request
}
Related
I'm trying to decide on a consistent response JSON structure and I found this SO answer.
I like the simplicity of JSend but now I'm wondering what is a clean way to implement that structure in express without having to manually create it each response or use a constructor in every controller method to help build the structure. I found jsend-express npm but it has so few downloads I'm worried about relying on it.
Can anyone recommend some ways to automatically enforce some of this structure in express myself?
However, I'm not sure why a status key is even necessary when the 3 states seem to already be covered by HTTP statuses and I don't see this key recommended in google's style guide, so that's another reason I may not want to use the jsend package and just do it myself to omit some keys and add later if needed.
This ended up being how I did it based on this SO answer.
I have a catch all error handler that adds the error key, but for all non-errors I wanted the data to be wrapped in a data key without having do it in every controller method by hand, or to call another function in every controller method before the res.json since that is also repetitive.
/**
* Nests all successful res data in a `data` key. Any additional meta-data
* that needs to be present at the top level json object can be added here.
* #param {request} _req
* #param {response} res
*/
const modifyResponseBody = (_req, res, next) => {
const resDotJson = res.json;
res.json = function (data) {
const isError = data?.hasOwnProperty?.("error") === true;
if (!isError) {
arguments[0] = { data: data };
}
resDotJson.apply(res, arguments);
};
next();
};
app.use(modifyResponseBody);
I have a custom logging function which is assigned to express requests req.log object using middleware.
The purpose of this is for the logging funtion to be able to read the request headers.traceid, before transmitting the log event to a seperate service.
This is working perfectly fine using middlware or with an extra parameter in the function, however to simplify the use of it.
What I'd really like to know if there's a way for the function to be able to read the req object from the scope it was called in, without referencing it either using middlware or as a function paramter?
// log.js
module.exports = () => {
console.log(...arguments)
const req = getVarFromParentScope("req") || undefined
const traceId = req?.headers.traceid || null
// POST { timestamp, traceId, args: { ...arguments } } to logging service
}
No, it isn't.
(And if it was, then the ability for a function to access a variable inside another function just because it was the calling function would make it very easy to write code that was very hard to debug.)
Нello! I am looking to call a function which has been passed to an expressRouter.post(...) call.
This expressRouter.post(...) call is occurring in a file which I am unable to modify. The code has already been distributed to many clients and there is no procedure for me to modify their versions of the file. While I have no ability to update this file for remote clients, other developers are able to. I therefore face the issue of this POST endpoint's behaviour changing in the future.
I am also dealing with performance concerns. This POST endpoint expects req.body to be a parsed JSON object, and that JSON object can be excessively large.
My goal is to write a GET endpoint which internally activates this POST endpoint. The GET endpoint will need to call the POST endpoint with a very large JSON value, which has had URL query params inserted into it. The GET's functionality should always mirror the POST's functionality, including if the POST's functionality is updated in the future. For this reason I cannot copy/paste the POST's logic. Note also that the JSON format will never change.
I understand that the issue of calling an expressjs endpoint internally has conventionally been solved by either 1) extracting the router function into an accessible scope, or 2) generating an HTTP request to localhost.
Unfortunately in my case neither of these options are viable:
I can't move the function into an accessible scope as I can't modify the source, nor can I copy-paste the function as the original version may change
Avoiding the HTTP request is a high priority due to performance considerations. The HTTP request will require serializing+deserializing an excessively large JSON body, re-visiting a number of authentication middlewares (which require waiting for further HTTP requests + database queries to complete), etc
Here is my (contrived) POST endpoint:
expressRouter.post('/my/post/endpoint', (req, res) => {
if (!req.body.hasOwnProperty('val'))
return res.status(400).send('Missing "val"');
return res.status(200).send(`Your val: ${req.body.val}`);
});
If I make a POST request to localhost:<port>/my/post/endpoint I get the expected error or response based on whether I included "val" in the JSON body.
Now, I want to have exactly the same functionality available, but via GET, and with "val" supplied in the URL instead of in any JSON body. I have attempted the following:
expressRouter.get('/my/get/endpoint/:val', (req, res) => {
// Make it seem as if "val" occurred inside the JSON body
let fakeReq = {
body: {
val: req.params.val
}
};
// Now call the POST endpoint
// Pass the fake request, and the real response
// This should enable the POST endpoint to write data to the
// response, and it will seem like THIS endpoint wrote to the
// response.
manuallyCallExpressEndpoint(expressRouter, 'POST', '/my/post/endpoint', fakeReq, res);
});
Unfortunately I don't know how to implement manuallyCallExpressEndpoint.
Is there a solution to this problem which excludes both extracting the function into an accessible scope, and generating an HTTP request?
This seems possible, but it may make more sense to modify req and pass it, rather than create a whole new fakeReq object. The thing which enables this looks to be the router.handle(req, res, next) function. I'm not sure this is the smartest way to go about this, but it will certainly avoid the large overhead of a separate http request!
app.get('/my/get/endpoint/:val', (req, res) => {
// Modify `req`, don't create a whole new `fakeReq`
req.body = {
val: req.params.val
};
manuallyCallExpressEndpoint(app, 'POST', '/my/post/endpoint', req, res);
});
let manuallyCallExpressEndpoint = (router, method, url, req, res) => {
req.method = method;
req.url = url;
router.handle(req, res, () => {});
};
How about a simple middleware?
function checkVal(req, res, next) {
const val = req.params.val || req.body.val
if (!val) {
return res.status(400).send('Missing "val"');
}
return res.status(200).send(`Your val: ${val}`);
}
app.get('/my/get/endpoint/:val', checkVal)
app.post('/my/post/endpoint', checkVal)
This code isn't tested but gives you rough idea on how you can have the same code run in both places.
The checkVal function serves as a Express handler, with request, response and next. It checks for params first then the body.
I have two LoopBack models, A and B. Part of their code is like this:
A.beforeRemote('create', function (ctx, unused, next) {
...
B.findById(idForB, callBack);
...
});
B.observe('access', function (ctx, next) {
const token = ctx.options && ctx.options.accessToken;
const userId = token && token.userId;
ctx.query = ctx.query ? ctx.query : {};
ctx.query.where = ctx.query.where ? ctx.query.where : {};
ctx.query.where.allowedUserId = userId;
});
Now, B's access observe hook has accessToken when REST calls are directly made from B/ API.
However, when making an API POST A/ API call, A's beforeRemote hook on create attempts to call B.findById which in turn triggers B's access observe hook, but in this scenario, there is no accessToken; not even option.
How do I propagate access information from A to B?
You pass it along in the options argument. As mentioned below, if you're doing something custom make sure the options.accessToken is set or set it yourself. findById etc already have the mechanism to provide the options-object.
https://loopback.io/doc/en/lb3/Using-current-context.html
Any additional context is passed in the “options” argument. Built-in
methods such as PersistedModel.find or PersistedModel.create already
accept this argument, custom user methods must be modified to accept
it too.
Whenever a method invokes another method, the “options” argument must
be passed down the invocation chain.
To seed the “options” argument when a method is invoked via a REST
call, the “options” argument must be annotated in remoting metadata
with a specific value set in the “http” property.
Optionally, applications can customize the value provided to “options”
when invoked via REST.
If I assigned the res (result) object to a module level property, will it be unique for each request, or could a secondary request that is started before the callback finishes overwrite it?
var moduleData = {};
router.route('/publishers/:id')
.get(function(req, res) {
var id = req.params.id;
// Assigning the res property to a module level property called `moduleData`
moduleData.res = res;
db.findById('publishers', id, function(error, publishers) {
someFurtherWork(publishers); // would rather not pass the res object around
});
});
function someFurtherWork(publishers) {
someWork(publishers, function(error, data) {
// NOW we send the data back to user... is `res` guranteed to be the same one that initiated the request?
moduleData.res.send(data);
});
}
The router is itself event driven, meaning that each .get() request is handled as a callback to the server, when the thread is available. This guarantees each response object is unique to the function. Will a module level property be overwritten by a second GET request here?
If so, what workarounds are there, because I don't want to pass around my response object to multiple chained callback functions, that don't use them until all the data is collected.
There's a good reason I'm doing this, because if I have a bunch of callbacks, and once they're all done, then I need my response object. I figured if I used the response as a module level property, it won't need to be passed around.
The unique scope of each request your app receives is the same as the scope of the first callback you provide to the router, any variable that is defined in the outer scope is global to all requests.
You have to move the declaration of your var ModuleData = {} to the top of the callback. And because you defined someFurtherWork(publishers) function inside the same callback then it will have access via the closure to ModuleData object and you can just use it.
And if what you only need is to have the res object available to your nested callback and function so you can just use it as long as they all have a common root scope which is the initial callback function. Aren't closures awesome!