NodeJs: Socket.io use() method - node.js

I can't find any document that make an understanding about use() method. Please explane socket.use() method.
Thanks a lot

socket.use() is basically where you can add middleware functions, which just means that the function passed as the parameter for thesocket.use() function is executed for every piece of info received.
Here's the socket.io docs
https://socket.io/docs/server-api/#socket-use-fn

socketio.use() method is same like as express_app.use() method , means both are used for passing middleware-functions , where middleware-functions can control/manipulate every upcoming requests/response on the server.

Related

How do Express router.param and router.route work in terms of defining URL parameter names?

I created a router file using Express. The callback functions reside in their discrete "controllers" files. Following is an excerpt of the parts relevant to my question, and lines such as require of controller functions have been omitted:
const express = require('express');
const router = express.Router();
// This should run first
router.param('coolParamName', validateParamBeforeHandlingReqs);
// Param name is ↑↑↑↑↑ "consumed" here, although NOT defined yet
// This should run after the above code
router.route('/').get(getAllUserNames).post(createUser);
router.route('/:coolParamName').get(getUserName).patch(updateUser).delete(deleteUser);
// Param name is ↑↑↑↑↑ defined here, and was consumed earlier - how?
As the comments explain, it seems like the param name has been defined as coolParamName on the bottom, but "consumed" by the code written above it. This feels strange to me, because I feel it's natural to define first and then use later - is it just me? Did I write a code that's against the intended design pattern?
I would like to understand how Express defines the name of param, and how router.param and router.router handle them.
router.param('coolParamName') essentially registers a callback that will get called for any route (in that router) that uses the :coolParamName parameter and matches the current request. The callback will get called once per request BEFORE the route that matches the request that contains the :coolParamName parameter.
It's kind of like middleware for a matching parameter. It allows you to automatically configure some setup code anytime that particular parameter is matched in a route.
FYI, I expect that router.param() may be one of the least used features of Express since it can be accomplished many other ways, but it probably works best for validation-type code that checks named properties for validity before the route itself gets called.
You could accomplish the same thing by just using a piece of middleware on that specific route too or even just calling a function inside the route handler. So, this is just a nicety feature if you happen to use the same parameter in multiple routes.

How to read nodejs documentation regarding callback parameters (node v8.x)

I am trying to understand the node.js documentation specifically for the https.get() method. https://nodejs.org/dist/latest-v8.x/docs/api/https.html#https_https_get_options_callback
What is unclear to me is the callback. The example in the document indicates the callback can take a res (response) object as its parameter but I am unsure if this is the only parameter it can take or more importantly where I can find the definition of the res object so I can know what properties and methods I can access on this object.
Is there a straightforward way to identify this?
I have read this thread: Trying to understand nodejs documentation. How to discover callback parameters and the answers seem to suggest that if there is a non-error argument that a callback can take it will be documented, but I am assuming that answer is outdated.
I've run into the same issue with many Node/NPM packages. Documentation sometimes does not describe the parameters well.
So, welcome to JavaScript in 2018! It's gotten a lot better, though, to be honest.
My go-to method is to try the methods and dump the information myself.
Try a console.dir(res) in your callback:
https.get('https://encrypted.google.com/', (res) => {
console.dir(res);
});
Alternatively, you can set a breakpoint in the callback and inspect it yourself. You can then probe the arguments object* to see what else, if anything, was passed as an argument, or do another console dump:
https.get('https://encrypted.google.com/', function (res) {
console.dir("args:", arguments);
console.dir("res:", res);
});
EDIT: Wait, apparently the arguments variable is not available to arrow functions, fixed the second example.
*From MDN:
The arguments object is not an Array. It is similar to an Array, but
does not have any Array properties except length.
From your link https://nodejs.org/dist/latest-v8.x/docs/api/https.html#https_https_get_options_callback, you can see that it works like the http version :
Like http.get() but for HTTPS.
With http.get() clickable.
On that page (https://nodejs.org/dist/latest-v8.x/docs/api/http.html#http_http_get_options_callback), we can see this :
The callback is invoked with a single argument that is an instance of http.IncomingMessage
With http.IncomingMessage clickable, linking this page :
https://nodejs.org/dist/latest-v8.x/docs/api/http.html#http_class_http_incomingmessage
I agree the Node documentation is not very clear about the callbacks in general, and that is a shame. You can still use IDEs with good intellisense (and JSDoc to identify the type of the function parameters), like VSCode.
Or you can use a debugger, always works :)
Edit: If you want to see all the parameters sent to a function, you can use the spread syntax like this :
function foo(...params) {
// Here params is an array containing all the parameters that were sent to the function
}
If you want the absolute truth, you can look at the implementation. Though that's fairly time consuming.
If you find that the documentation is wrong, or in this case could be improved by adding a sentence about the callback parameter to https.get(), please open an issue, or, better yet, a pull request. This is where the change needs to be made:
https://github.com/nodejs/node/blob/67790962daccb5ff19c977119d7231cbe175c206/doc/api/https.md

Express / Mongoose REST and middleware

If you apply middleware to a rest POST call and you provide an array of JSON objects as the req.body will the middleware iterate through each object and run for each one or will it just run once for the entire request body?
Ended up having to write my middleware in a way that can handle arrays and iterate through by using: for ( var i in req.body ) {...}.
There is no documentation on this and down voting for no research effort is asinine.
The answer is in fact that it only runs once for the request even if you provide an array. Hope this answer is helpful for someone else..

Replacement for req.param() that is deprecated in Express 4

We are migrating from ExpressJS 3 to ExpressJS 4, and we noted that the following APIs are being deprecated:
req.param(fieldName)
req.param(fieldName, defaultValue)
Is there a middleware that brings these APIs back, like other APIs that were 'externalized' from express to independent modules ?
EDITED:
Clarification - The need is an API that provides an abstracted generic access to a parameter, regardless to if it is a path-parameter, a query-string parameter, or a body field.
Based on Express Documentation, we should use like this
On express 3
req.param(fieldName)
On express 4
req.params.fieldName
Personally i prefer req.params.fieldName instead req.param(fieldName)
Why would you want to bring it back? There's a reason that it's been deprecated and as such you should probably move away from it.
The discussion on why they are deprecating the API is available at their issue tracker as #2440.
The function is a quick and dirty way to get a parameter value from either req.params, req.body or req.query. This could of course cause trouble in some cases, which is why they are removing it. See the function for yourself here.
If you are just using the function for url parameters, you can just replace it with this a check for req.query['smth'] or 'default':
var param_old = req.param('test', 'default');
var param_new = req.query['test'] || 'default';
(Please note that an empty string is evaluated to false, so they are not actually 100% equal. What you want is of course up to you, but for the most part it shouldn't matter.)
Ok, after reading the threads given in references by #Ineentho, we decided to come up with the following answer:
https://github.com/osher/request-param
A connect/express middleware to enable back the req.param(name,default) API deprecated in express 4
The middleware does not only brings back the goo'old functionality.
It also lets you customize the order of collections from which params are retrieved , both as default rule, and as per-call :-)
Have fun!

Expressjs one function to handle GET and POST

Is it is better to have a separate function to handle GET and POST requests for the same API endpoint or combine them into one function that discriminates based on the existence of req.body or req.params?
ie.
app.get('/api/profilepic', api.get_profilepic);
app.post('/api/profilepic', api.change_profilepic);
or:
app.get('/api/profilepic', api.profilepic);
app.post('/api/profilepic', api.profilepic);
If the latter, does expressjs provide a helper function to determine the request type? My approach so far to determine if req is POST requires underscore:
if (_.size(req.body) == 0)
There is no general rule, the best approach depends on the case you are working on. I think if you want an api endpoint that accept POST and GET requests combined, you should use express function all() like this:
app.all('/api/profilepic', api.get_profilepic);
You should use seperate endpoints for POST and GET when the handler function is not the same.
For more details see:
http://expressjs.com/en/guide/routing.html
Best practice is to separate concerns; therefore, you should have separate functions to handle each HTTP verb. This makes the code easier to maintain.

Resources